Skip to content Skip to sidebar Skip to footer

Python 3: The Visibility Of Global Variables Across Modules

Similar questions have been asked before: here, here and here, and I am aware of these. Say you have 2 modules where one has global variables that you want to read from in another

Solution 1:

from module import * binds the objects in module to like named variables in the current module. This is not a copy, but the addition of a reference to the same object. Both modules will see the same object until one of them rebinds the object. Modifying a mutable object doesn't rebind the variable so an action such as appending to a list is okay. But reassigning the the variable does rebind it. Usually the rebind is straight forward:

myvar = something_else

But sometimes its not so clear

myvar += 1

For immutable objects such as int or str, this rebinds the variable and now the two modules have different values.

If you want to make sure you always reference the same object, keep the namespace reference.


Post a Comment for "Python 3: The Visibility Of Global Variables Across Modules"