Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - What is the concept of namespace when importing a function from another module?

main.py:

from module1 import some_function
x=10
some_function()

module1.py:

def some_function():
    print str(x)

When I execute the main.py, it gives an error in the moduel1.py indicating that x is not available.

My understanding was that using from x import y in module main.py brings the definition/value of x.y in the local namespace of main.py. And since both the function definition and variable x are in local namespace of main.py, it should work ok. But this seems incorrct undersyanding. So what is the exact concept here? Any link to officcial python documentation for this concept?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Each module has its own global name space.

from module1 import some_function
x=10
some_function()

some_function uses module1.x in its definition, but you are setting x in the current module. This would work:

from module1 import some_function
import module1

module1.x = 10
some_function()

Note that you can't use from module1 import x, then set x = 10, because that import simply initializes a new name x to have the same initial value as module1.x; x = 10 then gives a new value to the new variable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...