[Python-bugs-list] [ python-Bugs-577972 ] Scope trouble with __init__.py

noreply@sourceforge.net noreply@sourceforge.net
Sat, 06 Jul 2002 10:06:07 -0700


Bugs item #577972, was opened at 2002-07-06 00:02
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=577972&group_id=5470

Category: Python Interpreter Core
Group: Python 2.2.1
>Status: Closed
>Resolution: Invalid
Priority: 5
Submitted By: Mike Romberg (romberg)
Assigned to: Nobody/Anonymous (nobody)
Summary: Scope trouble with __init__.py

Initial Comment:


  I think that there is a small problem with what gets
imported into the scope of an __init__.py module with
a package.  At least if this is the correct behavior it
seems a bit funny to me.

  Consider the following modules located in a subdirectory
of the load path called spam:

spam/
 
--------  spam/__init__.py ---------------
a = 1
from b import c
print "a = ", a


-------- spam/b.py -------------------
c = 2
import a

--------- spam/a.py -----------------
d = 3

  I would expect that when one imported the
spam package, you would see 'a = 1' displayed.
Instead you get 'a =  <module 'spam.a' from 'spam/a.py'>'.
So, it seems that python pulled in the 'a' symbol from b
and overwrote the one already in __init__.  This would
make sense if __init__ did a 'from b import *'.  But
I think the current behavior might be a bug.


----------------------------------------------------------------------

>Comment By: Jeremy Hylton (jhylton)
Date: 2002-07-06 17:06

Message:
Logged In: YES 
user_id=31392

The module __init__ is executed only once, but each 
import of a module within the package binds the 
module in the package's namespace.  Here's the series 
of events:
a = 1 # binds a
from b import c # binds c when it is done
# but first execute code in b
# which binds spam.b
import a # binds spam.a
# from b import c is done
print a # most recent binding is to module as side-
effect of sub-module import

You can see this effect most clearly if you have an 
empty __init__ and do a dir() of the package after doing 
several submodule imports.



----------------------------------------------------------------------

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=577972&group_id=5470