Import in python is static, any solution?

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 doesn't i change when foo.i changes?

+4
source share
4 answers

In import in bar.py , the identifier i to i in the module namespace bar.py , which points to the same address as the identifier named i in the module namespace foo.py

This is an important difference ... bar.i does not point to foo.i , but rather to the same space in memory where object 10 is stored, which points to foo.i at the same time. In python, variable names are not memory space .. They are an identifier pointing to memory space. When importing into a bar, you configure the local namespace identifier.

Your code behaves as expected until foo.fi() is called when the identifier i in the namespace foo.py is changed to point to literal 99, which is an object in memory, obviously in other than 10. Now the namespace at the level of the dict module for foo has i identification of another object in memory than the identifier i in bar.py.

Shane and rossfabricant have good suggestions for setting up modules to achieve what they want.

+7
source

What Ross says is to offset foo like this:

 _i = 10 def getI(): return _i def fi(): global _i _i = 99 

Then you will see that it works the way you want:

 >>> import foo >>> print foo.getI() 10 >>> foo.fi() >>> print foo.getI() 99 

It is also β€œbetter” in the sense that you avoid exporting global, but still provide read access.

+8
source

i inside foo.py is different from the value in bar.py When you are in bar.py :

 from foo import i 

This creates a new i in bar.py that references the same object as i in foo.py

Your problem: when you call foo.fi() and it does this:

 i = 99 

This assignment means that foo.py i points to another integer object ( 99 ). Integer objects are immutable (fortunately), so it only changes what foo.py i points to. Not bar.py i . bar.py i still points to the old object that he was pointing to earlier. (integer immutable object 10 )

You can check what I'm talking about by placing the following command in bar.py :

 print foo.i 

he should print 99 .

+3
source

You can call a function instead of referencing a global variable.

0
source

All Articles