Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverting the 'global <var>' statement

I am learning Python and just had this question. It possibly has no practical worth, I'm asking this out maybe because of a pedantic curiosity.

I have a function:

def f():
    x = 12    #this is a local variable
    global x  #this is a global I declared before
    x = 14    #changes global x

    <How can I return the local x?>

I'm aware that this is ugly and I do get a Syntax Warning. Just wanted to know how to "get back" my local variable.

Thanks to everyone.

like image 903
Learner Avatar asked Feb 16 '26 11:02

Learner


1 Answers

Your code isn't doing what you think it is and there's no way to change it do what you describe. You can't "revert" what globals does since it has no effect at run time.

The global keyword is interpreted at compile time so in the first line of f() where you set x = 12 this is modifying the global x since the compiler has decided the x refers to the x in the global namespace throughout the whole function, not just after the global statement.

You can test this easily:

>>> def g():
...     x = 12
...     y = 13
...     global x
...     print "locals:",locals()
...
<stdin>:4: SyntaxWarning: name 'x' is assigned to before global declaration
>>> g()
locals: {'y': 13}

The locals() function gives us a view of the local namespace and we can see that there's no x in there.

The documentation says the following:

Names listed in a global statement must not be used in the same code block textually preceding that global statement.

Names listed in a global statement must not be defined as formal parameters or in a for loop control target, class definition, function definition, or import statement.

The current implementation does not enforce the latter two restrictions, but programs should not abuse this freedom, as future implementations may enforce them or silently change the meaning of the program.

Just give the local variable a different name.

like image 168
Dave Webb Avatar answered Feb 18 '26 00:02

Dave Webb