This question already has answers here:
Visibility of global variables in imported modules
(9 answers)
Closed 5 years ago.
All of the following is in one file:
def inner_foo(in_arg):
global x;
x += 99
return in_arg + 1
def outer_foo(in_arg):
global x;
x = 0
output = inner_foo(in_arg)
return output
result = outer_foo(5)
print("result == ", result)
print("x == ", x)
It works just fine when it is all in one file. Here is what gets printed:
result == 6
x == 99
However, if we try to split the program across multiple files, we run into problems.
# CONTENTS OF inner_foo.py
def inner_foo(in_arg):
global x;
x += 99
return in_arg + 1
Here is the other file:
# CONTENTS OF outer_foo.py
from inner_foo import inner_foo
def outer_foo(in_arg):
global x
x = 0
output = inner_foo(in_arg)
return output
result = outer_foo(5)
print("result == ", result)
print("x == ", x)
We get an error NameError: name 'x' is not defined on the line x += 99 inside inner_foo.py
Changing the import statement to include x (from inner_foo import inner_foo, x) gives us:
ImportError: cannot import name 'x'
Python "global" scope is actually module-level, as you inferred when you tried to import. The problem is, when you do x += 1, that is the equivalent to x = x + 1, but x has never been defined in your module. So, suppose we have a.py:
def f():
global x
x += 1
There is no x in a, there is only f. So now, let's open up a REPL:
>>> import a
>>> a.f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/juan/workspace/temp/globals_modules/a.py", line 3, in f
x += 1
NameError: name 'x' is not defined
And, as stated above, "global scope" is actually module-level scope, so f's global scope is module a's namespace, not necessarily the caller's global scope, i.e.:
>>> x = 0
>>> a.f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/juan/workspace/temp/globals_modules/a.py", line 3, in f
x += 1
NameError: name 'x' is not defined
So, actually, it is looking for x in a's namespace, so if we do the following:
>>> a.x = 0
>>> a.f()
>>> a.x
1
>>> a.f()
>>> a.x
2
It works! So to put it as succinctly as possible:
>>> a.f.__globals__ is globals()
False
However!
Now that you are armed with this knowledge, do not go down this design path. Relying on changing global state across modules is a path to sorrow. Don't do it, it isn't recommended because generations of coders have found this is bad. Redesign your approach, and you will build more robust, easier to reason-about, and less buggy software.
Related
I'm trying to make a little choose your own adventure game for fun and can't find a way to make this work. I want to be able to have a consistent pick up method where a specific action adds one to a variable and unlocks lines of dialogue under other actions. What I've got right now is something like this.
item = 0
while True:
act = input()
if "action" in act:
if(item != 1):
print("You don't have that item.")
continue
else:
print("You use the item.")
continue
if "take item" in act:
print("You take the item.")
global item
item = item + 1
continue
The issue I'm finding is that when I try to set the global variable, the program claims a syntax warning:
main.py:107: SyntaxWarning: name 'item' is assigned to before global declaration global item
since the variable is stated before the global, but if I don't state the variable before hand, the system I have in place to prevent the wrong dialogue from printing won't work. How do I have a conditional global variable that updates an existing local variable?
TLDR
You don't need the global keyword. Remove that line and your code will work.
Short Explanation
In Python, everything is "global" (not accurate, I will explain in long explanation) so you rarely need to use the global keyword. You can try the following code in the interactive Python REPL:
>>> def test(y):
... return x, y
...
>>> test(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in test
NameError: name 'x' is not defined
>>> x = 4
>>> test(3)
(4, 3)
Here, I'm using a function as an example, if and while/for loops are exactly the same.
I'm declaring a function called test that takes in a parameter y, but it will return the tuple (x, y). Here, x is undefined. You would expect that it returns an error, but it actually doesn't until you run it.
When we run test(3), Python will complain that x is not defined so it cannot run the function. However, if we define x = 4 even after our function declaration, the function will work. Hence test(3) will return (4, 3). Here, x is treated as a global variable.
Long Explanation
>>> x = 3
>>> y = 4
>>> def test2():
... x = 1
... y = 2
... return x, y
...
>>> test2()
(1, 2)
>>> x
3
>>> y
4
>>>
Notice that y is not touched, even though it's clearly being assigned a different value in the function test2.
How is this possible? Actually, Python functions technically do have a scope of their own, and changes to function variables are isolated and do not change the variables of the same name outside the function. Loops and if statements don't have their own scope, so the variables inside if statements are the exact variables outside them.
>>> x = 3
>>> y = 4
>>> if True:
... x = 1
... y = 2
...
>>> x
1
>>> y
2
When you reference a variable in functions, Python will check if a value is assigned to a variable of that name in that function (either as a parameter or inside the function block). If there is a variable with that name, Python will use the variable in the function (within the scope of the function). If not, Python will try to look for a function that's in the scope outside (either another function or the global scope). If Python searched till the global scope and there is no variable of that name, it will finally produce an error.
>>> x = 3
>>> y = 4
>>> def function1():
... x = 4 # this x is being used
... def function2():
... print(x)
... function2()
...
>>> function1()
4
>>> def test3():
... x = 1
... y = 2
... return (x, y)
...
>>> test3()
(1, 2)
>>> x
3
>>> y
4
This means, only when you are trying to change the value of a variable outside of the current scope, you will use the global keyword. However, this is BAD PRACTICE. Whenever you find yourself doing this, you need to think about whether you should refactor your code to using classes. It's a very bad practice to change the value of global variables inside functions no matter the language you are using.
>>> x = 3
>>> y = 4
>>> def test4():
... global x, y # refers to the global x and y
... x = 1
... y = 2
... return (x, y)
...
>>> test4()
(1, 2)
>>> x
1
>>> y
2
>>> x = 1
>>> def f():
... print x
...
>>> f()
1
>>> x = 1
>>> def f():
... x = 3
... print x
...
>>> f()
3
>>> x
1
>>> x = 1
>>> def f():
... print x
... x = 5
...
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
UnboundLocalError: local variable 'x' referenced before assignment
>>> x = 1
>>> def f():
... global x
... print x
... x = 5
... print x
...
>>> f()
1
5
>>> x
5
How to treat the variable "x" inside the function as local without altering the global one when I have print statement above the variable assignment?
I expect the result of "x" to be 5 inside the function and the global x should be unaltered and remains the same in value (i.e) 1
I guess, there is no keyword called local in python contrary to global
>>> x = 1
>>> def f():
... print x
... global x
... x = 5
...
<stdin>:3: SyntaxWarning: name 'x' is used prior to global declaration
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.
Source.
It's true there's no local keyword in Python; instead, Python has this rule to decide which variables are local.
Any variable in your function is either local or global. It can't be local in one part of the function and global in another. If you have a local variable x, then the function can't access the global x. If you want a local variable while accessing the global x, you can call the local variable some other name.
The behaviour is already what you want. The presence of x = inside the function body makes x a local variable which entirely shadows the outer variable. You're merely trying to print it before you assign any value to it, which is causing an error. This would cause an error under any other circumstance too; you can't print what you didn't assign.
If you want to create tens of thousands of variables in Python, is there a way to do this in a for statement. What I want is a code that, when given a number and a value, can create that number of variables and assign them that value.
def createVars(num, somevalue):
for x in range(num):
var1 = somevalue
var2 = somevalue
The idea is for the loop to continue making variables with reliable names(var3, var4, etc.) and assigning them to some given value. How could you make this system that could create variables without explicitly having to name all of them?
def createVars(num, somevalue):
l = [{'var'+str(x):somevalue} for x in xrange(num)]
return l
You can use globals():
>>> for i in xrange(10):
... globals()["x%d" % i] = i
...
>>> x0
0
>>> x1
1
>>> x2
2
>>> x10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x10' is not defined
In python (tested on 2.7.6) all variables are
statically bound to a scope at compile time. This process is well
described in http://www.python.org/dev/peps/pep-0227/ and
http://docs.python.org/2.7/reference/executionmodel.html
It is explicitly stated that "If a name binding operation occurs
anywhere within a code block, all uses of the name within the block
are treated as references to the current block."
A function is a code block so the following code with fail because x
is assigned after its use (so at compile time it is defined local
because it is assigned somewhere in the function, but at execution
time, it is used before being bound).
x = 1
def f():
print x
x = 2
print x
>>> f()
Traceback (most recent call last):
File "<pyshell#46>", line 1, in <module>
f()
File "<pyshell#45>", line 2, in f
print x
UnboundLocalError: local variable 'x' referenced before assignment
A class is also a code block, so we should observe exactly the
same behavior. But this is not what I observe.
Look at this example:
x = 1
class C():
y = x + 10
x = 2
def __init__(self):
print C.y
>>> C.x
2
>>> C.y
11
>>> C()
11
<__main__.C instance at 0x00000000027CC9C8>
As the class definition is a code block, any assignment within this
block should make the variable local. So x should be local to the
class C, so y = x + 10 should result in an UnboundLocalError.
Why there is not such error?
Yes - it seems that the documentation is rather misleading. A class definition doesn't actually work quite the same as other normal blocks:
global_one = 0
class A(object):
x = global_one + 10
global_one = 100
y = global_one + 20
del global_one
z = global_one + 30
a = A()
print a.x, a.y, a.z, global_one
results in: 10, 120, 30, 0
if you try the same thing with a function, you get an UnboundLocalError on your first access of global_one.
The reason for this is that class definitions as normal have access to the parent scope, however, all name assignments do NOT modify a local scope, but in fact are captured into the class's data attributes dictionary. There are hints about this in the documentation, but it's certainly not obvious.
Could someone explain why the following program fails:
def g(f):
for _ in range(10):
f()
def main():
x = 10
def f():
print x
x = x + 1
g(f)
if __name__ == '__main__':
main()
with the message:
Traceback (most recent call last):
File "a.py", line 13, in <module>
main()
File "a.py", line 10, in main
g(f)
File "a.py", line 3, in g
f()
File "a.py", line 8, in f
print x
UnboundLocalError: local variable 'x' referenced before assignment
But if I simply change the variable x to an array, it works:
def g(f):
for _ in range(10):
f()
def main():
x = [10]
def f():
print x[0]
x[0] = x[0] + 1
g(f)
if __name__ == '__main__':
main()
with the output
10
11
12
13
14
15
16
17
18
19
The reason I am confused is, if from f() it can't access x, why it becomes accessible if x is an array?
Thanks.
But this answer says the problem is with assigning to x. If that's it,
then printing it should work just fine, shouldn't it?
You have to understand the order in which things happen. Before your python code is even compiled and executed, something called a parser reads through the python code and checks the syntax. Another thing the parser does is mark variables as being local. When the parser sees an assignment in the code in a local scope, the variable on the lefthand side of the assignment is marked as local. At that point, nothing has even been compiled yet--let alone executed, and therefore no assignment takes place; the variable is merely marked as a local variable.
After the parser is finished, the code is compiled and executed. When execution reaches the print statement:
def main():
x = 10 #<---x in enclosing scope
def f():
print x #<-----
x = x + 1 #<-- x marked as local variable inside the function f()
the print statement looks like it should go ahead and print the x in the enclosing scope (the 'E' in the LEGB lookup process). However, because the parser previously marked x as a local variable inside f(), python does not proceed past the local scope (the 'L' in the LEGB lookup process) to lookup x. Because x has not been assigned to in the local scope at the time 'print x' executes, python spits out an error.
Note that even if the code where an assignment occurs will NEVER execute, the parser still marks the variable on the left of an assignment as a local variable. The parser has no idea about how things will execute, so it blindly searches for syntax errors and local variables throughout your file--even in code that can never execute. Here are some examples of that:
def dostuff ():
x = 10
def f():
print x
if False: #The body of the if will never execute...
a b c #...yet the parser finds a syntax error here
return f
f = dostuff()
f()
--output:--
File "1.py", line 8
a b c
^
SyntaxError: invalid syntax
The parser does the same thing when marking local variables:
def dostuff ():
x = 10
def f():
print x
if False: #The body of the if will never execute...
x = 0 #..yet the parser marks x as a local variable
return f
f = dostuff()
f()
Now look what happens when you execute that last program:
Traceback (most recent call last):
File "1.py", line 11, in <module>
f()
File "1.py", line 4, in f
print x
UnboundLocalError: local variable 'x' referenced before assignment
When the statement 'print x' executes, because the parser marked x as a local variable the lookup for x stops at the local scope.
That 'feature' is not unique to python--it happens in other languages too.
As for the array example, when you write:
x[0] = x[0] + 1
that tells python to go lookup up an array named x and assign something to its first element. Because there is no assignment to anything named x in the local scope, the parser does not mark x as a local variable.
The reason is in first example you used an assignment operation, x = x + 1, so when the functions was defined python thought that x is local variable. But when you actually called the function python failed to find any value for the x on the RHS locally, So raised an Error.
In your second example instead of assignment you simply changed a mutable object, so python will never raise any objection and will fetch x[0]'s value from the enclosing scope(actually it looks for it firstly in the enclosing scope, then global scope and finally in the builtins, but stops as soon as it was found).
In python 3x you can handle this using the nonlocal keyword and in py2x you can either pass the value to the inner function or use a function attribute.
Using function attribute:
def main():
main.x = 1
def f():
main.x = main.x + 1
print main.x
return f
main()() #prints 2
Passing the value explicitly:
def main():
x = 1
def f(x):
x = x + 1
print x
return x
x = f(x) #pass x and store the returned value back to x
main() #prints 2
Using nonlocal in py3x:
def main():
x = 1
def f():
nonlocal x
x = x + 1
print (x)
return f
main()() #prints 2
The problem is that the variable x is picked up by closure. When you try to assign to a variable that is picked up from the closure, python will complain unless you use the global or nonlocal1 keywords. In the case where you are using a list, you're not assigning to the name -- You can modify an object which got picked up in the closure, but you can't assign to it.
Basically, the error occurs at the print x line because when python parses the function, It sees that x is assigned to so it assumes x must be a local variable. When you get to the line print x, python tries to look up a local x but it isn't there. This can be seen by using dis.dis to inspect the bytecode. Here, python uses the LOAD_FAST instruction which is used for local variables rather than the LOAD_GLOBAL instruction which is used for non-local variables.
Normally, this would cause a NameError, but python tries to be a little more helpful by looking for x in func_closure or func_globals 2. If it finds x in one of those, it raises an UnboundLocalError instead to give you a better idea about what is happening -- You have a local variable which couldn't be found (isn't "bound").
1python3.x only
2python2.x -- On python3.x, those attributes have changed to __closure__ and __globals__ respectively
The problem is in the line
x = x + 1
This is the first time x being assigned in function f(), telling the compiler that x is a local name. It conflicts with the previous line print x, which can't find any previous assignment of the local x.
That's where your error UnboundLocalError: local variable 'x' referenced before assignment comes from.
Note that the error happens when compiler tries to figure out which object the x in print x refers to. So the print x doesn't executes.
Change it to
x[0] = x[0] + 1
No new name is added. So the compiler knows you are referring to the array outside f().