I have the following file app.py
class Baz():
def __init__(self, num):
self.a = num
print self.a
def foo(num):
obj = Baz(num)
and the second file main.py
from app import foo
foo(10)
Running the file python main.py
gives the correct output.
Now in the second file, I'm just importing the function not the class, although successful execution of my function requires the class as well.
When importing the function does Python automatically import everything else which is needed to run that function, or does it automatically search for the class in the current directory?
Python does not automatically do any of these things.
When you import something from a module (in this case, the
app
module), Python first runs all the code in the corresponding file (app.py
). The code in the fileapp.py
which you've written does two things:Baz
foo
When the function
foo
runs, Python looks forBaz
in the module thatfoo
is part of, and only there. (Well, it also checks local variables defined in the functionfoo
, but you don't have any of those exceptobj
.) Specifically, it looks forapp.Baz
. If you alter yourmain.py
to do the same search:you will see that
app.Baz
is the class you defined inapp.py
.If you put the definition of class
Baz
in yet another file, and if you don't import that file, Python will not run it. This shows that Python does not automatically import dependencies. In particular, supposeapp.py
containsand
baz.py
containsand
main.py
is unchanged. You'll get an error because Python has not run the code to define the classBaz
.As @DavidZ already mentioned the whole Python file gets compiled when we import it. But another special thing happens when a function body is parsed, a function knows which variables it should look for in local scope and which variables it should look for in global scope(well there are free variables too).
So, here
Baz
must be fetched from global scope.Well, each function has a special attribute
__globals__
attached to it which contains its actual global namespace. Hence, that's the source ofBaz
:So, app's module dictionary and
foo.__globals__
point to the same object:Due to this even if you define another variable named
Baz
inmain.py
after importingfoo
it will still access the actualBaz
.From data-model page:
__globals__ func_globals
: