Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
700 views
in Technique[技术] by (71.8m points)

function - Does Python import statement also import dependencies automatically?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).

>>> import dis
>>> dis.dis(foo)
  7           0 LOAD_GLOBAL              0 (Baz)
              3 LOAD_FAST                0 (num)
              6 CALL_FUNCTION            1
              9 STORE_FAST               1 (obj)
             12 LOAD_CONST               0 (None)
             15 RETURN_VALUE

So, here Baz must be fetched from global scope.

But how to identify this global scope when we import app.py in another file?

Well, each function has a special attribute __globals__ attached to it which contains its actual global namespace. Hence, that's the source of Baz:

>>> foo.__globals__['Baz']
<class __main__.Baz at 0x10f6e1c80>

So, app's module dictionary and foo.__globals__ point to the same object:

>>>sys.modules['app'].__dict__ is foo.__globals__ 
True

Due to this even if you define another variable named Baz in main.py after importing foo it will still access the actual Baz.

From data-model page:

__globals__ func_globals:

A reference to the dictionary that holds the function’s global variables — the global namespace of the module in which the function was defined.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...