Why doesn't Python remember the initial directory?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Aug 19 23:38:03 EDT 2012


On Mon, 20 Aug 2012 01:57:46 +0000, kj wrote:

> In <roy-CA6D77.17031119082012 at news.panix.com> Roy Smith <roy at panix.com>
> writes:
> 
>>In article <k0rj38$2gc$1 at reader1.panix.com>, kj <no.email at please.post>
>>wrote:
> 
>>> As far as I've been able to determine, Python does not remember
>>> (immutably, that is) the working directory at the program's start-up,
>>> or, if it does, it does not officially expose this information.
[...]
> 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__.

Possibly not in the face of chmod.


> That's a weakness, IMO.

Certainly.


> One manifestation of this
> weakness is that os.chdir breaks inspect.getmodule, at least on Unix.

At the very least, it can do so under some circumstances.

By the way, inspect.currentframe is quite problematic. Although it is 
given a public name, it is just a thin wrapper around sys._getframe which 
is not just *named* as a private function, but also states clearly in the 
documentation:

"This function should be used for internal and specialized purposes only."

So I'm not sure that fixing problems with inspect.currentframe will be 
high on anyone's priority.


[...]
> 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.

I'm not convinced that this is necessary for the example you give. 
Perhaps modules need to store absolute pathnames rather than relative 
ones?

os.chdir probably breaks a lot of things. Python operates under the 
assumption that the working directory does not change. If you change it, 
it's your responsibility to deal with it.

Apart from shell scripting languages, do other languages cope well with 
having the working directory changed?

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

Not so much. More of, "yes, that's a bug, but it's not an important bug. 
If you have a patch for fixing it, we'll consider it, but if you don't, 
we've got about two thousand more important bugs and features to get 
through first."

Your chances of getting this fixed will be *much* improved if you can 
demonstrate a genuine problem that can't easily be fixed by just telling 
the programmer "don't change working directories, or if you do, you need 
to change back again before doing X, Y or Z".

Personally, I think that trying to fix all the things that break if you 
chdir is not worthwhile, but having Python record the directory you 
started with in (say) sys.startingdirectory might be a worthwhile feature 
request.



-- 
Steven



More information about the Python-list mailing list