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.