how does import work ?

Michele Simionato mis6 at pitt.edu
Wed Nov 20 09:33:24 EST 2002


Suppose I have a module where two functions f1 and f2 are defined and
suppose that f2 calls f1 internally. This is an example:

# -- begin module f1f2.py --

def f1():
    print "Called f1()"

def f2():
    print "Called f2()"
    f1()

# -- end module f1f2.py --

Suppose now I import ONLY the function f2, but not f1:

>>> from f1f2 import f2

Then, if I call f2,  I would expect an error since f2 requires f1 but 
I have NOT imported f1. Nevertheless it works:

>>> f2()
Called f2()
Called f1()

therefore Python has imported f1 too, but is some hidden way, since
f1 is not in the current namespace dictionary:

>>> vars()
{'__builtins__': <module '__builtin__' (built-in)>, 
'__name__': '__main__', 'f2': <function f2 at 0x815779c>, 
'__doc__': None}

This behavior is quite confusing to me, somebody can explain what is
happening ?

--
Michele Simionato - Dept. of Physics and Astronomy
210 Allen Hall Pittsburgh PA 15260 U.S.A.
Phone: 001-412-624-9041 Fax: 001-412-624-9163
Home-page: http://www.phyast.pitt.edu/~micheles/



More information about the Python-list mailing list