Nested module import clutters package namespace?

Matthew Woodcraft mattheww at chiark.greenend.org.uk
Fri Feb 29 12:54:25 EST 2008


<ruediger.kupper at honda-ri.de> wrote:
> I'd be grateful for help with a problem of package and module=20
> namespaces. The behaviour I observe is unexpected (to me), and I=20
> couldn't find the answer in the docs, the tutorial, or the mailing=20
> list archive. So here we go:

> I have a package named 'pack'. Apart from the '__init__.py' file the=20
> directory contains two modules 'x.py' and 'y.py':
>
> pack/
>       __init__.py
>       x.py
>       y.py
>
> The files have the following contents:

> ==== __init__.py ====
> import x
> =====================
>
> ==== x.py ===========
> import y
> =====================
>
> ==== y.py ===========
> pass
> =====================

> I then do
>  >>> import pack

> This
> (1) introduces variable 'x' bound to <module 'pack.x'>
>      in pack's namespace (expected)
> (2) introduces variable 'q' bound to <module 'pack.y'>
>      in x's namespace (expected)
> but also
> (3) introduces variable 'y' bound to <module 'pack.y'>
>      in pack's namespace (*totally unexpected*)


That's right, Python has behaved like this since packages were introduced.

There's no doubt that this is intentional, but the state of the
documentation is rather embarrassing. The reference manual's
explanation of package imports consists largely of this reference:

<<XXX Can't be bothered to spell this out right now; see the URL
http://www.python.org/doc/essays/packages.html for more details,>>

The referenced essay is over 10 years old and unsurprisingly somewhat
out of date.

This behaviour gets even more exciting when circular imports are
involved. See for example message
slrnbm2ajt.np4.stain at ozelot.stud.ntnu.no on this list.

-M-




More information about the Python-list mailing list