Why doesn't Python remember the initial directory?

alex23 wuwei23 at gmail.com
Sun Aug 19 22:57:44 EDT 2012


On Monday, 20 August 2012 11:57:46 UTC+10, kj  wrote:
> This means that no library code can ever count on, for example,
> being able to reliably find the path to the file that contains the
> definition of __main__.  That's a weakness, IMO.

No, it's not. It's a _strength_. If you've written a library that requires absolute knowledge of its installed location in order for its internals to work, then I'm not installing your library.

> When I do this on my system (OS X + Python 2.7.3), the script bombs
> at the last print statement, because the second call to inspect.getmodule
> (though not the first one) returns None.

So, uh, do something sane like test for the result of inspect.getmodule _before_ trying to do something invalid to it?

> I don't know of any way to fix inspect.getmodule that does not
> involve, directly or indirectly, keeping a stable record of the
> starting directory.

Then _that is the answer_. YOU need to keep "a stable record":

    import inspect 
    import os 
    
    THIS_FILE = os.path.join(os.getcwd(), '<this_module_name>.py')
    
    frame = inspect.currentframe() 
    print inspect.getmodule(frame).__name__ 
    
    os.chdir('/some/other/directory')
    
    print inspect.getmodule(frame, _filename=THIS_FILE).__name__ 

> But, who am I kidding?  What needs fixing, right?  That's not a
> bug, that's a feature!  Etc.

Right. Because that sort of introspection of objects is rare, why burden the _entire_ language with an obligation that is only required in a few places?

> By now I have learned to expect that 99.99% of Python programmers
> will find that [blah blah blah, whine whine whine]. 
> Pardon my cynicism, but the general vibe from the replies I've
> gotten to my post (i.e. "if Python ain't got it, it means you don't
> need it") is entirely in line with these expectations.

Oh my god, how DARE people with EXPERIENCE in a language challenge the PRECONCEPTIONS of an AMATEUR!!! HOW DARE THEY?!?!



More information about the Python-list mailing list