Copies of variables are created from the file import variable
If I
from file import variable
and is varable
changed in the module file, the value is variable
not updated. If I
import file
varaible is updated file.variable
.
Is there a way to selectively import variables from a module, place them in the local module scope, and reflect updates.
source to share
Not. In Python, all variables are references (pointers) to objects. Simple assignments when rebinding assigned names - they point to different objects. That is, if you have two names, a
and b
, that point to the same object, say 42
and you assign to b
another object, for example "Don't Panic"
, a
before 42
.
a = b = 42
b = "Don't Panic"
print a
This remains true whether the names are associated with the same module or different modules.
If you don't want this behavior, don't use an alternate name for the same object. As you found, you should import file
and should access it as file.variable
, not from file import variable
. The latter is equivalent to:
import file
variable = file.variable
del file
So, under the hood, it from ... import
does the assignment of a new name. The name is the same as the name it already has, but it is in a different scope and is a new object reference.
Another possible solution is to use mutable objects, so you don't need to do simple assignments. For example, if a
- it is a list, you can change a[0]
and a[2]
etc. Whatever you like, without changing what it points to a
. You can even remap the entire contents of an object without rebonding name: a[:] = [1, 2, 3]
. Since you are changing the object itself, and not what is indicated in any of the names, the changes can be seen through any name.
source to share