This question already has answers here:
Using global variables in a function
(25 answers)
Closed 2 years ago.
I am a c++ programmer and am learning pygame so I am very new to python. I noticed this behavior of functions and don't know what to do about it:
let's say we have a global variable:
x = 10
Now let's say we have a function that changes the value of x:
def foo():
x = 100
Now, inside my main pygame loop, if I call foo(), the variable x is still 10 after the function call. How is this happening???
Inside the function local scope value of x is changed. The x defined outside the function has global scope. To change global value try global var_name statement inside function before updating value
def foo():
global x
x = 100
Inside your function, you implicitly create another variable x, and then set it to 100. To change the global variable try this:
def foo():
global x
x = 100
Related
This question already has answers here:
UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)
(14 answers)
Closed 7 months ago.
I was learning about closures in Lua and came accross this code that works in Lua:
function newcounter()
local i = 0
function dummy()
i = i + 1
return i
return dummy
x = newcounter()
print(x())
-- this outputs 1, i.e., dummy uses the i variable from its enclosing function newcounter
I thought Python also supports a similar closure. So I tried the following code in Python3:
def nc():
i = 0
def dummy():
i = i + 1
return i
return dummy
x = nc()
print(x())
However, when I run the above Python code, I get the error that i is accessed before being assigned!
Traceback (most recent call last):
File "/tmp/test.py", line 9, in <module>
print(x())
File "/tmp/test.py", line 4, in dummy
i = i + 1
UnboundLocalError: local variable 'i' referenced before assignment
Does this mean Python does not support closures? Or am I misunderstanding something about closures?
Python decides the scope of variables based on where it finds assignments to them. Because you have an assignment to i in the form i = ..., i will be a local variable scoped to dummy by default, but you can override that with a nonlocal statement:
def nc():
i = 0
def dummy():
nonlocal i
i = i + 1
return i
return dummy
x = nc()
print(x())
So yes, Python has closures.
Assigning to a name within a Python function makes it local by default, from the beginning of the function to the end. If you want to assign to names while having them remain tied to the closure scope, you must explicitly declare said name nonlocal:
def nc():
i = 0
def dummy():
nonlocal i # Makes code work as expected by forcing loads and stores to apply to
# closed-upon i
i = i + 1
return i
return dummy
Python supports closures. The issue you're dealing with here has to do with how scoping works, which is explained here: UnboundLocalError on local variable when reassigned after first use. Note that you can get the same error by referencing a global variable.
Here's an example closure:
def nc(i):
def dummy():
return i
return dummy
x = nc(9)
i = 8
print(x()) # -> 9
This question already has an answer here:
Python - Passing variables through functions
(1 answer)
Closed 1 year ago.
How can I get this to work
Should I use a gloabl variable or a args?
I'm very confused.
def getvenueurl():
# code as part of a loop
venueURList.append(tMD)
# end loop
def getraceurl():
print(venueURList)
getvenueurl()
getraceurl()
In this case you can define the variable outside of functions scope.
Exemple:
venueURList = []
def getvenueurl():
# code as part of a loop
venueURList.append(tMD)
# end loop
def getraceurl():
print(venueURList)
getvenueurl()
getraceurl()
Just return the list in a function. Store the returned value in a variable and pass it through a new function.
def getvenueurl():
# code as part of a loop
venueURList.append(tMD)
return venueURList
# end loop
def getraceurl(lst):
print(lst)
venueList = getvenueurl()
getraceurl(venueList)
Or another option would be to use global venueURList
In order to access a global variable inside a function, you must type:
global venueURList
before it is referenced or modified (in your case, append and print)
Generally, it is a better idea to pass the global variable into the parameter and return it instead.
def getvenueurl(venueList):
venueList.append(tMD)
return venueList
This question already has answers here:
Short description of the scoping rules?
(9 answers)
Closed 2 years ago.
I know about nonlocal keyword and how to fix this error but I am getting a behaviour that I am not understanding in the code below. If you run this, there is no problem
def test( root):
x=2
def f2(r):
print("***")
x=r #Adding this line is ok
print("----",x)
f2(root)
return x
test(4)
Now try changing x=r to be be the last line in f2 does not work as below
def test( root):
x=2
def f2(r):
print("***")
print("----",x)
x=r #Gives an error "local variable 'x' referenced before assignment"
f2(root)
return x
test(4)
Thanks
You have two variables named 'x', in two different scopes. I would not recommend doing this; it can lead to a lot of confusion, leading to bugs in the program.
I would not suggest fixing this with keywords. Rename one of the variables. If you do, the error becomes clear.
def test( root):
x_test=2
def f2(r):
print("***")
print("----",x_f2)
x_f2=r
f2(root)
return x_test
test(4)
Clearly, x_f2 is being referenced before assignment. When you write the code like this, the error is clear.
This is exactly what your code is doing; it is just not clear because you have two variables with the same name, in different scopes.
The 'x' inside f2 is a local variable in the function, and you can not use it before assigning it. The fact that in the outer scope there is a different variable named 'x' which has been assigned, does not change that.
the problem is in line 5 where you printed x in print("----",x),
it doesnt know the x in f2 function so you cant print it
if you want to use that x=2 in f2() you should pass it to it , or using the global key or ...
In the first example, you're assigning a new local variable x that is independent of the x in the outer scope. Since you assign this value before you use it, that's fine. The x that you assign 4 to is the one that's local to f2, which is why when you return x from test it's the original 2 value.
In the second example, you do the same thing of assigning a new local variable x (which causes the outer scope's x to be shadowed, same as before), but this time you reference it before you actually do the assignment. That's what generates the error.
If you didn't assign x at all, then it wouldn't be shadowed and you would be able to print its value from the outer scope (meaning you'd see its value as 2, not 4):
>>> def test( root):
... x=2
... def f2(r):
... print("***")
... print("----",x)
... f2(root)
... return x
...
>>> test(4)
***
---- 2
2
This question already has answers here:
Is it possible to modify a variable in python that is in an outer (enclosing), but not global, scope?
(9 answers)
Closed 5 months ago.
I am confused with the global keyword behavior in below code snippet, I was expecting 30, 30, 30 in all 3 prints.
def outer_function():
#global a ###commented intentionally
a = 20
def inner_function():
global a
a = 30
print('a =',a)
inner_function()
print('a =',a)
a = 10
outer_function()
print('a =',a)
#Output:
#30
#20 #Expecting 30 here
#30
All the confusion coming from "global a" after outer function definition. As my understanding at this point of time is " All the reference and assignment to variable become globally reflected on declaration of global keyword on that variable". If I am uncommenting that first global statement I am getting expected output 30,30,30.
Why global declaration inside inner_function and value change does not reflect on 2nd print i:e to outer_function(or outer scope), whereas got reflected in global namespace.
A common acronym to be familiar with is LEGB:
Local
Enclosed
Global
Built-in
This is the order in which Python will search the namespaces to find variable assignments.
Local
The local namespace is everything that happens within the current code block. Function definitions contain local variables that are the first thing that is found when Python looks for a variable reference. Here, Python will look in the local scope of foo first, find x with the assignment of 2 and print that. All of this happens despite x also being defined in the global namespace.
x = 1
def foo():
x = 2
print(x)
foo()
# prints:
2
When Python compiles a function, it decides whether each of the variables within the definition code block are local or global variables. Why is this important? Let's take a look at the same definition of foo, but flip the two lines inside of it. The result can be surprising
x = 1
def foo():
print(x)
x = 2
foo()
# raises:
UnboundLocalError: local variable 'x' referenced before assignment
This error occurs because Python compiles x as a local variable within foo due to the assignment of x = 2.
What you need to remember is that local variables can only access what is inside of their own scope.
Enclosed
When defining a multi-layered function, variables that are not compiled as local will search for their values in the next highest namespace. Here is a simple example.
x = 0
def outer_0():
x = 1
def outer_1():
def inner():
print(x)
inner()
outer_1()
outer_0()
# print:
1
When inner() is compiled, Python sets x as a global variable, meaning it will try to access other assignments of x outside of the local scope. The order in which Python searches for a value of x in moving upward through the enclosing namespaces. x is not contained in the namespace of outer_1, so it checks outer_0, finds a values and uses that assignment for the x within inner.
x --> inner --> outer_1 --> outer_0 [ --> global, not reached in this example]
You can force a variable to not be local using the keywords nonlocal and global (note: nonlocal is only available in Python 3). These are directives to the compiler about the variable scope.
nonlocal
Using the nonlocal keyword tells python to assign the variable to first instance found as it moves upward through the namespaces. Any changes made to the variable will be made in the variable's original namespace as well. In the example below, when 2 is assigned x, it is setting the value of x in the scope of outer_0 as well.
x = 0
def outer_0():
x = 1
def outer_1():
def inner():
nonlocal x
print('inner :', x)
x = 2
inner()
outer_1()
print('outer_0:', x)
outer_0()
# prints:
inner : 1
outer_0: 2
Global
The global namespace is the highest level namespace that you program is running in. It is also the highest enclosing namespace for all function definitions. In general it is not good practice to pass values in and out of variables in the global namespace as unexpected side effects can occur.
global
Using the global keyword is similar to non-local, but instead of moving upward through the namespace layers, it only searches in the global namespace for the variable reference. Using the same example from above, but in this case declaring global x tells Python to use the assignment of x in the global namespace. Here the global namespace has x = 0:
x = 0
def outer_0():
x = 1
def outer_1():
def inner():
global x
print('inner :', x)
inner()
outer_1()
outer_0()
# prints:
0
Similarly, if a variable is not yet defined in the global namespace, it will raise an error.
def foo():
z = 1
def bar():
global z
print(z)
bar()
foo()
# raises:
NameError: name 'z' is not defined
Built-in
Last of all, Python will check for built-in keywords. Native Python functions such as list and int are the final reference Python checks for AFTER checking for variables. You can overload native Python functions (but please don't do this, it is a bad idea).
Here is an example of something you SHOULD NOT DO. In dumb we overload the the native Python list function by assigning it to 0 in the scope of dumb. In the even_dumber, when we try to split the string into a list of letters using list, Python will find the reference to list in the enclosing namespace of dumb and try to use that, raising an error.
def dumb():
list = 0
def even_dumber():
x = list('abc')
print(x)
even_dumber()
dumb()
# raises:
TypeError: 'int' object is not callable
You can get back the original behavior by referencing the global definition of list using:
def dumb():
list = [1]
def even_dumber():
global list
x = list('abc')
print(x)
even_dumber()
dumb()
# returns:
['a', 'b', 'c']
But again, DO NOT DO THIS, it is bad coding practice.
I hope this helps bring to light some of how the namespaces work in Python. If you want more information, chapter 7 of Fluent Python by Luciano Ramalho has a wonderful in-depth walkthrough of namespaces and closures in Python.
From the documentation:
The global statement is a declaration which holds for the entire
current code block. It means that the listed identifiers are to be
interpreted as globals.
Note it only applies to current code block. So the global in inner_function only applies within inner_function. Outside of it, the identifier is not global.
Note how “identifier” is not the same as “variable”. So what it tells the interpreter is “when I use identifier a within this code block, do not apply normal scope resolution, I actually mean the module-level variable, ”.
Just uncomment your global command in the outer_function, otherwise you're declaring a local variable with value 20, changing a global variable then printing that same local variable.
It's not a good idea use global variabilities. If you want only reset the value of a variable, you just use this lines:
def outer_function():
a = 20
def inner_function():
a = 30
print('a =',a)
return a
a = inner_function()
print('a =',a)
return a
a = 10
a = outer_function()
print('a =',a)
This question already has answers here:
Is it possible to modify a variable in python that is in an outer (enclosing), but not global, scope?
(9 answers)
Closed 8 years ago.
In the 2nd case below, Python tries to look for a local variable. When it doesn't find one, why can't it look in the outer scope like it does for the 1st case?
This looks for x in the local scope, then outer scope:
def f1():
x = 5
def f2():
print x
This gives local variable 'x' referenced before assignment error:
def f1():
x = 5
def f2():
x+=1
I am not allowed to modify the signature of function f2() so I can not pass and return values of x. However, I do need a way to modify x. Is there a way to explicitly tell Python to look for a variable name in the outer scope (something similar to the global keyword)?
Python version: 2.7
In Python 3.x this is possible:
def f1():
x = 5
def f2():
nonlocal x
x+=1
return f2
The problem and a solution to it, for Python 2.x as well, are given in this post. Additionally, please read PEP 3104 for more information on this subject.
def f1():
x = { 'value': 5 }
def f2():
x['value'] += 1
Workaround is to use a mutable object and update members of that object. Name binding is tricky in Python, sometimes.