os.chdir() considered harmful

Donn Cave donn at u.washington.edu
Tue Sep 26 12:38:33 EDT 2000


Quoth Guido van Rossum <guido at beopen.com>:
| In a neat little piece of code posted by Tim, I found this gem:
|
| >         # This seems a little-known trick in Python:  changing to the
| >         # current directory allows the subsequent isdir-in-a-loop to
| >         # work on just the file name, instead of making the OS reparse
| >         # the whole darn path from the root again each time.
| >         # Depending on the OS, can save gobs of time.
|
| I have no objection to using this in a small self-contained program
| like Tim's example.  However I would like to warn that using
| os.chdir() is not always a safe practice!  The current directory is
| used for several purposes, like interpreting pathnames entered by the
| user, and importing Python modules supplied by the user.
|
| If you change the current directory, you may not find the files that
| the user asked you to open, or you may find that surprising modules
| are imported (the current directory is first in Python's module path
| when Python is invoked without a script).
|
| The current directory is also shared between threads, so in a
| multi-threaded program, it's doubly scary.
|
| My personal guideline for os.chdir() is to only use it in a main
| Python program / script, never in a module imported by others.

No argument with this, but it occurs to me that conversely, a module
imported by others should import its modules up front, and not later
during execution, because the program may indeed change its current
working directory.

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list