Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why reset python global value doesn't take effect

Tags:

python

global

Just confused about global value in Python, here are two piece of code

#gl.py

import cli

a = 1    
print "gl 1: %d %d" % (id(a), a)


def reset():
    global a
    a = 7
    print "reset 1: %d %d" % (id(a), a)


if __name__ == '__main__':
    cli.handler(reset)
    print "gl 2: %d %d" % (id(a), a)

the cli code

#cli.py

def handler(func):
    from gl import a
    print "cli 1: %d %d" % (id(a), a)
    func()
    print "cli 2: %d %d" % (id(a), a)

The result of execution is

$ python gl.py
gl 1: 150847672 1
gl 1: 150847672 1
cli 1: 150847672 1
reset 1: 150847600 7
cli 2: 150847672 1    #Why value doesn't change
gl 2: 150847600 7

Here I don't understand after "function reset()" execution, the result of global value doesn't change in cli.py(cli 2: 150847672 1), but back to gl.py, global value does change!!

like image 900
linbo Avatar asked Mar 06 '13 05:03

linbo


People also ask

How do you reset global variables in Python?

You can change the value of a Python global variable by simply assigning it a new value (redeclaring). To delete a variable, use the keyword del .

Can global variables be changed in Python?

In Python, global keyword allows you to modify the variable outside of the current scope. It is used to create a global variable and make changes to the variable in a local context.

Should you avoid using global variables in Python?

While in many or most other programming languages variables are treated as global if not declared otherwise, Python deals with variables the other way around. They are local, if not otherwise declared. The driving reason behind this approach is that global variables are generally bad practice and should be avoided.

Are global variables Pythonic?

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function's body, it's assumed to be a local unless explicitly declared as global.


2 Answers

Two concepts are missing here

  • Globals are globals to modules and not across modules

Refer: http://legacy.python.org/doc/essays/ppt/hp-training/sld036.htm

Refer: http://docs.python.org/release/2.4/ref/global.html

  • Variables are imported as Values and not by reference

Refer: https://stackoverflow.com/a/3338357/977038

If you need to share Global variables across modules refer How do I share global variables across modules?

like image 122
Abhijit Avatar answered Oct 15 '22 21:10

Abhijit


Your gl module is imported twice into two different namespaces

try this:

import sys
print sys.modules['__main__'].a
print sys.modules['gl'].a
like image 42
John La Rooy Avatar answered Oct 15 '22 19:10

John La Rooy