Saturday, March 03, 2007

The Implied Module Path

We all know there is an implied path to import from for the main module, but it seems a few people get mixed about the details of how this works. In particular, it seems that this path is being confused for the current working directory. Here is a little note to help remember the distinction.
  • Any module implicitly can import packages and modules in the same directory its file resides in, which is os.path.dirname(the_module.__file__)
  • Often you run a script, when starting out, from its own directory, so that this implied path is the current working directory. This fact is purely a coincidence.
The result boils down simply to understanding that any import can be relative to the module it appears in, and if you run a local (not system-wide available) script, that just happens to be your current directory, by coincidence.

2 comments:

Anonymous said...

I believe that under Jython, the environment CWD is used, rather than the directory that the module is in.

Patrick said...

Calvin,

Interested in a Harrisburg Python Group? We're meeting on Tuesday April 3rd, at the Camp Hill Panera Bread (corner of RT 11 and 581):

http://tinyurl.com/2mdzs5

(google doesn't know where Panera is, Arby's is right next door)

Mailing list info at:
https://nimrod.pearcec.com/mailman/listinfo/python

I write here about programming, how to program better, things I think are neat and are related to programming. I might write other things at my personal website.

I am happily employed by the excellent Caktus Group, located in beautiful and friendly Carrboro, NC, where I work with Python, Django, and Javascript.