Import 'filename'? (was Re: Cross-reference 'import' in a class hierarchy)

Chris Reedy creedy at
Tue Apr 8 22:28:40 CEST 2003

Ben Finney wrote:
> On Tue, 08 Apr 2003 15:44:10 +1200, Greg Ewing (using wrote:
>>It's been suggested before (and I happen to agree) that Python should
>>provide a general way of making *relative* references to modules or
> I continue to be amazed that there's simply no way to say
>   import "../foo/"
> as should be possible to implement any well-architected class hierarchy.
> Anyone who can show me otherwise gets a jelly baby.

I had to think about this one for a while. Here's the issue I see:

What exactly does import '../foo/' actual do?

If you're still interested, read on.


There are three ways (no wait -- make that four ways) to refer to a 

(1) It's name as defined by searching the file system using PYTHONPATH:

   This is what you get when you say import It looks for 
a file named in a directory <dir>/MyApp/foo where <dir> is in 

(2) It's name as defined in sys.modules.

   This is what you get when you say import and 
sys.modules[''] already exists.

(3) It's name as defined via variable lookup in the local or global 

   That is, when you write x =, you expect that MyApp 
refers to a module object that has an attribute foo that is a module 
object that .... Remember that if you "import as eek" you 
can now refer to eek.f().

(4) It's actual location in the file system, i.e. 

   Note that this one doesn't correspond to the others in any well 
defined way: could be loaded as module 'ook', 'foo.ook', ... or, 
as '__main__'. In the former cases, the module would have a __file__ 
attribute giving the correct location. In the latter case it doesn't, 
but sys.path[0] would give you the directory?!

Based on some reading in the email archives, there is clearly a desire 
(maybe a mandate by the BDFL) that some sort of correspondence be 
guaranteed to exist between the above four definitions (especially 1, 2, 
and 3).


So my question is what does import '../foo/' mean in this context. 
What it's supposed to mean relative to (4) above seems obvious.

However, what it's supposed to mean relative to (2) and (3) is not at 
all clear. In particular, what name(s) would be added to the local 
dictionary and what name would be added to sys.modules?

Also, relative to (1), what would it mean if there is an that can 
be found via PYTHONPATH and it isn't the one you just loaded.

   Pant, pant,

This is informal and not an official Mitretek Systems position.
Dr. Christopher L. Reedy, Senior Principal Software Engineer
Mitretek Systems, 3150 Fairview Park Drive South, Falls Church, VA 
Email: creedy at  Phone: (703) 610-1615  FAX: (703) 610-2203

More information about the Python-list mailing list