foo.py :
i = 10 def fi(): global i i = 99
bar.py :
import foo from foo import i print i, foo.i foo.fi() print i, foo.i
This is problematic. Why does i not change when foo.i changes?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
What
importdoes inbar.pyis set up an identifier callediin thebar.pymodule namespace that points to the same address as the identifier callediin thefoo.pymodule namespace.This is an important distinction…
bar.iis not pointing tofoo.i, but rather to the same space in memory where the object10is held thatfoo.ihappens to point to at the same time. In python, the variable names are not the memory space… they are the identifier that points to a memory space. When you import in bar, you are setting up a local namespace identifier.Your code behaves as expected until
foo.fi()is called, when the identifieriin the foo.py namespace is changed to point to the literal 99, which is an object in memory obviously at a different place than 10. Now the module-level namespace dict forfoohasiidentifying a different object in memory than the identifieriin bar.py.Shane and rossfabricant have good suggestions on how to adjust your modules to achieve what you want.