[Python-Dev] Another Strategy for Relative Import

Chris and Ann Reedy chrisandannreedy at comcast.net
Tue Dec 23 15:03:37 EST 2003

Ken Manheimer wrote:
> Even using the leading '.' syntax, it would be good to have a specific
> identifier for the containing package, realized in each module and
> respected as a special identifier by the package machinery.  I like
> '__pkg__':
>   import __pkg__.sibling                # == 'import .sibling'
> and
>   import __pkg__.__pkg__.uncle          # == 'import ..uncle'
>   import __pkg__.__pkg__.uncle.cousin   # == 'import ..uncle.cousin'
> I think the leading '.' dot forms are a lot nicer, but the presence of
> a module named '__pkg__' would be useful for programmatically mucking
> navigating the package structure.


Knowing that the statement:

  import foo.bar

has the effect of setting the variable foo to reference package foo,
if the variable foo already references something else, I was wondering
if it would make sense to changes the semantics of import so that if the
variable foo is already assigned and is a package (or maybe a module in
some cases), then importing foo.bar would have the effect of importing
the module or package bar within foo, using foo.__path__ to search for the
module bar and foo.__name__ + '.bar' as the name of the module.

It seems to me that such an approach might be used in a number of cases:

1. If there is a standard name for the parent of a package, e.g. __pkg__,


just works.

2. This approach allows the following kind of thing to work:

if <something>:
  import xyz as util
  import xyz_old as util

import util.bar

3. This could be used to clean up the problem with os.path. The idea here
is that since initialization of os creates the attribute os.path which
references a module, then:

  import os.path

would have the effect of importing os and then noting that os.path
exists and
is a module, so no further work is required.

I haven't (yet?) attempted to work out whether this could be used to
handle all
the use cases for relative import.


P.S. I've been lurking on this list for a about six months. I just moved between
coasts (US) and things are still a mess. I would like to get more
involved with
Python. I'll send a message in the near future introducing myself.

More information about the Python-Dev mailing list