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
1.3k views
in Technique[技术] by (71.8m points)

python - Importing a py file within itself

This is test.py:

import sys

a = 50
b = [1,2]

def change():
    print "Here 1"
    import test
    print "Here 2"
    test.a = -1
    test.b = [0,1]
    return

def main():
    print "Here 3"
    change()
    print "Here 4"
    print a, b

if 1:
    main()

The above python code when ran on system generates the following output:

Here 3
Here 1
Here 3
Here 1
Here 2
Here 4
-1 [0, 1]
Here 2
Here 4
50 [1, 2]

What I am confused why is not there an infinite loop of "Here 1 Here 3" outputs. How can the print a, b outputs can be justified?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

When you run the file as a script, it is not considered to be the test module. It is considered to be the __main__ module.

When execution hits import test, a second execution of the file starts, where the module is considered to be test.

When execution hits import test again, Python recognizes that it's already importing test and does not reexecute the module. Instead, it merely loads the half-initialized test module object into the current namespace and continues on. Python's optimistic assumption is that you've written the code so that the contents of test won't be needed until the import finishes.

When execution hits the assignments to test.a and test.b, that affects the test module, but not __main__, despite the fact that they came from the same file. Thus, the print a, b from the imported module reflects the new values, while the print a, b from __main__ reflects the initial values.


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

...