+ 7
[PYTHON] GOLBAL VARIABLES
Hye everyone.is it possible to share global variables across modules? Till the time I noticed that yes we can share global variables. But how? And will be appreciable if someone explain with examples.
3 Antworten
+ 3
Maybe inside class
+ 2
Hi! When you create a variable in the module layer (that is a global variable, a variable that is not created inside a function without the global declaration), it becomes an attribute to other modules. So to get it from an other module you just import it:
# module1.py (file 1)
X = 88
—————————
# module2.py (file 2)
import module1
print(f”{module1.X=}”)
# - - - << run module2.py >> - - -
- - -
88
module1.X =88
>>>
Now X is shared between the two modules. And acctually, you can even change the value of X in module1 from module2, even if this is not a very good idea, because it is a very implicit act:
# module2.py (file 2 - extended)
import module1
print(f”{module1.X=}”)
module1.X = 66 # Remember it was 88...
print(f”{module1.X=}”)
# - - - << run module2.py again >> - - -
- - -
88
module1.X =88
module1.X =66
>>>
Now try to do a module3.py that import module1, and import it at the end of module2. You will see that it still gives that module1.X = 66.
Regards /Per B
0
A very simple example
from math import pi
print(pi)