If I
from file import variable
and the varable is changed in module file, the variables value is not updated.
If I
import file
the varaible file.variable is updated.
Is there a way of selectively importing variables from a module, placing them in the modules local scope and having the updates reflected.
-
1What kind of variable is it? If an int, float, bool or a string, than it is immutable.David Robinson– David Robinson2013年04月17日 20:04:15 +00:00Commented Apr 17, 2013 at 20:04
-
1It Started as None. Then it was assigned a file handle.Robert Jacobs– Robert Jacobs2013年04月17日 20:50:29 +00:00Commented Apr 17, 2013 at 20:50
1 Answer 1
No. In Python, all variables are references (pointers) to objects. Simple assignments in re-bind the names being assigned—they point them to different objects. That is, if you have two names, a and b, that point to the same object, say 42, and you assign b to a different object, say "Don't Panic", a still points to 42.
a = b = 42
b = "Don't Panic"
print a
This remains true whether the names involved are in the same module or different modules.
If you do not want this behavior, do not use an additional name for the same object. As you have found, you should import file and access it as file.variable rather than from file import variable. The latter is equivalent to:
import file
variable = file.variable
del file
So, under the hood, from ... import is doing an assignment of a new name. The name is the same as the name it already has, but it's in a different scope and is a new reference to the object.
Another possible solution is to use mutable objects so that you don't need to do simple assignments. For example, if a is a list, then you can modify a[0] and a[2] and so on all you like without ever changing what a points to. You can even reassign the whole content of the object without re-binding the name: a[:] = [1, 2, 3]. Since you are changing the object itself, not what any of the names point to, the changes can be seen through any name.
3 Comments
from file import variable is also creating a new binding thismodule.variable to the same object bound to file.variable. (In other words, it's basically like doing import file; variable = file.variable; del file.) Because I think that's half of what the OP was confused by.import SelfFile then SelfFile.Var is equivalent to global Var.