Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python global operator emulation

Tags:

python

in Lutz's book I read how to emulate global operator in a function body. I created p.py file in documents folder:

var = 0
def func():
    import p #import itself
    p.var = 15
func()
print(var)

output:

15
0

I thought is is supposed to simply print 15, but by some reason it also added 0 to output. So I'm wandering why has it happened.

for example, when i do the same thing in terminal, but in the main module, it works as I want:

var = 0
def func():
    import __main__ #import itself
    __main__.var = 15
func()
print(var)

and output is

15

I have python 3.7.7

like image 835
Ice Cube Avatar asked Mar 29 '26 17:03

Ice Cube


1 Answers

Files are not modules: files are used to define modules. If you run p.py as a script that contains import p, there are two modules, __main__ and p, both created from the same file, but each with its own global namespace.

like image 155
chepner Avatar answered Mar 31 '26 07:03

chepner