how does import work ?

Andrew Wilkinson ajw126NO at SPAMyork.ac.uk
Wed Nov 20 09:39:47 EST 2002


It's imported everything in the module f1f2 into a module namespace, it's
then created a link from the namespace where you've imported the module from
to the f1f2 namespace.
When you call f2() you're actually executing it in the namespace for f1f2 so
it has access to everything in that namespace.

HTH,
Andrew Wilkinson

"Michele Simionato" <mis6 at pitt.edu> wrote in message
news:2259b0e2.0211200633.2ed7e075 at posting.google.com...
> 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