gCharlie = 0
gJeff = 0
def Bob ():
Charlie = gCharlie
Jeff = gJeff
Number = int(input("Hello and Welcome to Charlie's Number Guessing Game. Enter a nonnegative number from 0 to 10 not counting 0. "))
This code gives me this error in Python 3.2:
UnboundLocalError: local variable 'gCharlie' referenced before assignment
What does this local variable error mean?
inside the Scope of your function you must have reassigned gJeff and gCharlie, which created them as new local variables. To tell python that you're using the globals, change the top of your function to look like this.
def Bob():
global gCharlie
global gJeff
Charlie=gCharlie
without telling python that you're using the globals, it tries to reference local gCharlie and gJeff variables, which as it says, have not been assigned at that point in your function. The reason people are getting it to work is because they're using only the code you've posted. You can reference globals without explicitly saying so ONLY if you don't change their values within the function referencing them.
As a rule python searches in this order for a variable name: local scope, any def it is nested inside of, global, built ins. Bbecause gJeff and gCharlie are local variables in your function, it stops there, unless you tell it otherwise.
If you want to see this in action try to look at this
x=5
def useX():
x=0 #this is a local variable
print "in function: ", x
def main():
print "in main(1): ", x
useX()
print "in main(2): ", x
main()
this will output
in main(1): 5
in function: 0
in main(2): 5
because within the function, x is created as a new local variable. Adding a global x statement to the useX function would change the last line to print "0" instead of "5"
It might be due to there is gCharlie = inside a function (note: the first letter is g).
Use parameters instead of globals:
def bob(charlie=0, jeff=0):
number = int(input("..."))
# ...
bob(charlie=3)
It means that you're assigning to gCharlie in the part of the function you didn't show, and so the Python compiler has marked it as a local variable. As such, you're accessing it before it exists. Use nonlocal or global to solve.
Two previous answers here are correct, but both are a bit unclear. I'll show with some examples:
The code you show will work fine:
>>> gCharlie = "Global!"
>>>
>>> def foo():
... print(gCharlie)
...
>>> foo()
Global!
>>> print(gCharlie)
Global!
So that's not the problem at all. However, you can't assign global variables inside a function:
>>> gCharlie = "Global!"
>>> def foo():
... gCharlie = "Local!"
... print(gCharlie)
...
>>> foo()
Local!
>>> print(gCharlie)
Global!
As you see, the global variable gCharlie did not change. This is because you did not modify it, you created a new local variable, with the same name. And this is the cause of the error:
>>> gCharlie = "Global!"
>>> def foo():
... oldCharlie = gCharlie
... gCharlie = "Local!"
... print(gCharlie)
...
>>> foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in foo
UnboundLocalError: local variable 'gCharlie' referenced before assignment
The hint is in the error. It says local variable gCharlie. The problem is not the inability to access the global gCharlie, but that the local one hasn't been created yet.
The fix is to specify that you don't want to create a local variable, but that you want to modify the global one. You do this with the global keyword.
>>> gCharlie = "Global!"
>>> def foo():
... global gCharlie
... oldCharlie = gCharlie
... gCharlie = "Local!"
... print(gCharlie)
...
>>> foo()
Local!
>>> print(gCharlie)
Local!
As you see now, you modified the global variable.
That said, global variables are usually a bad idea. Avoid them. Try to pass in the variables as parameters instead.
Related
This question already has answers here:
Using global variables in a function
(25 answers)
Closed 5 months ago.
I know I should avoid using global variables in the first place due to confusion like this, but if I were to use them, is the following a valid way to go about using them? (I am trying to call the global copy of a variable created in a separate function.)
x = "somevalue"
def func_A ():
global x
# Do things to x
return x
def func_B():
x = func_A()
# Do things
return x
func_A()
func_B()
Does the x that the second function uses have the same value of the global copy of x that func_a uses and modifies? When calling the functions after definition, does order matter?
If you want to simply access a global variable you just use its name. However to change its value you need to use the global keyword.
E.g.
global someVar
someVar = 55
This would change the value of the global variable to 55. Otherwise it would just assign 55 to a local variable.
The order of function definition listings doesn't matter (assuming they don't refer to each other in some way), the order they are called does.
Within a Python scope, any assignment to a variable not already declared within that scope creates a new local variable unless that variable is declared earlier in the function as referring to a globally scoped variable with the keyword global.
Let's look at a modified version of your pseudocode to see what happens:
# Here, we're creating a variable 'x', in the __main__ scope.
x = 'None!'
def func_A():
# The below declaration lets the function know that we
# mean the global 'x' when we refer to that variable, not
# any local one
global x
x = 'A'
return x
def func_B():
# Here, we are somewhat mislead. We're actually involving two different
# variables named 'x'. One is local to func_B, the other is global.
# By calling func_A(), we do two things: we're reassigning the value
# of the GLOBAL x as part of func_A, and then taking that same value
# since it's returned by func_A, and assigning it to a LOCAL variable
# named 'x'.
x = func_A() # look at this as: x_local = func_A()
# Here, we're assigning the value of 'B' to the LOCAL x.
x = 'B' # look at this as: x_local = 'B'
return x # look at this as: return x_local
In fact, you could rewrite all of func_B with the variable named x_local and it would work identically.
The order matters only as far as the order in which your functions do operations that change the value of the global x. Thus in our example, order doesn't matter, since func_B calls func_A. In this example, order does matter:
def a():
global foo
foo = 'A'
def b():
global foo
foo = 'B'
b()
a()
print foo
# prints 'A' because a() was the last function to modify 'foo'.
Note that global is only required to modify global objects. You can still access them from within a function without declaring global.
Thus, we have:
x = 5
def access_only():
return x
# This returns whatever the global value of 'x' is
def modify():
global x
x = 'modified'
return x
# This function makes the global 'x' equal to 'modified', and then returns that value
def create_locally():
x = 'local!'
return x
# This function creates a new local variable named 'x', and sets it as 'local',
# and returns that. The global 'x' is untouched.
Note the difference between create_locally and access_only -- access_only is accessing the global x despite not calling global, and even though create_locally doesn't use global either, it creates a local copy since it's assigning a value.
The confusion here is why you shouldn't use global variables.
You can directly access a global variable inside a function. If you want to change the value of that global variable, use "global variable_name". See the following example:
var = 1
def global_var_change():
global var
var = "value changed"
global_var_change() #call the function for changes
print var
Generally speaking, this is not a good programming practice. By breaking namespace logic, code can become difficult to understand and debug.
As others have noted, you need to declare a variable global in a function when you want that function to be able to modify the global variable. If you only want to access it, then you don't need global.
To go into a bit more detail on that, what "modify" means is this: if you want to re-bind the global name so it points to a different object, the name must be declared global in the function.
Many operations that modify (mutate) an object do not re-bind the global name to point to a different object, and so they are all valid without declaring the name global in the function.
d = {}
l = []
o = type("object", (object,), {})()
def valid(): # these are all valid without declaring any names global!
d[0] = 1 # changes what's in d, but d still points to the same object
d[0] += 1 # ditto
d.clear() # ditto! d is now empty but it`s still the same object!
l.append(0) # l is still the same list but has an additional member
o.test = 1 # creating new attribute on o, but o is still the same object
Here is one case that caught me out, using a global as a default value of a parameter.
globVar = None # initialize value of global variable
def func(param = globVar): # use globVar as default value for param
print 'param =', param, 'globVar =', globVar # display values
def test():
global globVar
globVar = 42 # change value of global
func()
test()
=========
output: param = None, globVar = 42
I had expected param to have a value of 42. Surprise. Python 2.7 evaluated the value of globVar when it first parsed the function func. Changing the value of globVar did not affect the default value assigned to param. Delaying the evaluation, as in the following, worked as I needed it to.
def func(param = eval('globVar')): # this seems to work
print 'param =', param, 'globVar =', globVar # display values
Or, if you want to be safe,
def func(param = None)):
if param == None:
param = globVar
print 'param =', param, 'globVar =', globVar # display values
You must use the global declaration when you wish to alter the value assigned to a global variable.
You do not need it to read from a global variable. Note that calling a method on an object (even if it alters the data within that object) does not alter the value of the variable holding that object (absent reflective magic).
I have two samples:
One:
import math
def my_function():
print(math.pi)
math.pi = 3
print(math.pi)
my_function()
Output:
3.141592653589793
3
Two:
a = 0
def my_function():
print(a)
a = 3
print(a)
my_function()
Output:
UnboundLocalError: local variable 'a' referenced before assignment
So what is the difference between them? I thought both math.pi and a were global in this case and it should produce UnboundLocalError.
If you do variable assignment within function the global variable would be ignored and won't be accessible within function execution, in sample with math lib you do not override name math itself, that's why it works. Snipped below would give you same error with math lib:
import math
def my_function():
print(math.pi)
math = 1
my_function()
You can use statement global before accessing variable, but if you will do any assignment later you will override global variable, so it's better to ALWAYS avoid doing that.
import math
def my_function():
global math
print(math.pi)
math = 1
print(math) # -> <module 'math' from ...
my_function() # -> 3.14159265359
print(math) # -> 1
In the first function, the variable is math, not math.pi. Since you're not assigning to math, it doesn't become a local variable. Assigning to an attribute of a variable is not the same thing as assigning to the variable itself.
If you changed the function to
def my_function():
print(math.pi)
math = 3
print(math.pi)
you would get the same kind of error as in the second function:
UnboundLocalError: local variable 'math' referenced before assignment
This has been answered a few times on SO before.
A variable is local to a function if there's a statement assigning it inside that function.
In your instance a = 3 defines a as local variable inside of your function. The first print(a) tries to access it, but it's not assigned a value yet.
That's why you see:
UnboundLocalError: local variable 'a' referenced before assignment.
The global instance created by a = 0 plays no role here.
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)
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
There is this code:
def f():
x = m
m = 2
def g():
x = m
f() # UnboundLocalError: local variable 'm' referenced before assignment
g() # NameError: global name 'm' is not defined
In both function bodies there is used variable m which is not defined when used but the error messages are different. Do Python know what variables are defined in function before using them (like in function f)? Why the error messages are different?
If there is an assignment to a variable anywhere in a function, then it is considered a local variable everywhere in that function. This means that for the function f(), even though the assignment to m happens after the attempt to access m, the line x = m will only look for the name m within the local scope. This is why the error message for f() refers to m as a local variable.
In the function g() there is no assigment to m, so the line x = m will look for m using the order described here:
the innermost scope, which is searched first, contains the local
names
the scopes of any enclosing functions, which are searched starting with the nearest enclosing scope, contains non-local, but also non-global names
the next-to-last scope contains the current module’s global names
the outermost scope (searched last) is the namespace containing built-in names
The error message for g(), "global name 'm' is not defined", refers to the global scope because that is the last location that was searched (except built-in, but it would be confusing to have a message like "the name 'm' was not found in the built-in namespace").
Note that you can use the global or nonlocal statements to change this behavior (nonlocal only exists in Python 3.x).
Python checks it as soon as you call it.
When importing, and typing directly into the interpreter, it only cares if you broke any syntax rules. it doesnt care about locals or globals at this level.
>>> def foo():
... print locals()
... bar = 34
... print locals()
... DIP = SET
...
>>>
>>> foo()
{}
{'bar': 34}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in foo
NameError: global name 'SET' is not defined
it runs from top to bottom, and checks locals() and globals() if it sees that variable then its okay and does whatever with it.
it even works with definitions and sub definitions.. or anything else you are assigning
>>> def foo():
... bar()
... def bar():
... print("never gonna give you up")
...
>>>
>>> foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in foo
UnboundLocalError: local variable 'bar' referenced before assignment
Yes. If you assign to a variable at any point in a function (without using the global keyword), Python treats all references to that name in the function as local.
When you execute a function, you actually invoke __call()__ on a function object.
The function object is created in the scripts global namespace when the script is parsed.
Created, but not executed.
As part of the parsing process, the objects namespace is computed. So the interpreter can actually know which variable exists and when.
def f():
x = m
m = 2
When the above function parsed python thinks that m is local variable as it finds m = 2, so when the function is actually called x = m will raise error as m is not defined yet in local scope.
def g():
x = m
In this python thinks that m is going to be some value from the global scope, it searches the global namespace first and then built-ins, but when m is not found anywhere the error is raised.
>>> m = 1
>>> def g():
x = m
>>> g() #works fine because `m` is found in global scope
>>> def g():
x = sum
>>> g() # sum is found in built-ins
To modify a global variable use global:
>>> m = 1
>>> def g():
global m
m += 1
...
>>> g()
>>> m
2
You need to use global m inside the function
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.
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.
I very much doubt that it can be done.
>>> x = 1
>>> def f():
... x = 12
... global x
... print x
...
<stdin>:3: SyntaxWarning: name 'x' is assigned to before global declaration
>>> f()
12
>>> x
12
As you can see, even without an explicit assignment to x after the global keyword, python syncs up the the values of the two. To see why, you have to disassemble it.
>>> dis.dis(f) # different f with print statement removed for clarity
2 0 LOAD_CONST 1 (12)
3 STORE_GLOBAL 0 (x)
3 6 LOAD_CONST 0 (None)
9 RETURN_VALUE
>>>
The global keyword isn't represented here at all but the assignment statement gets compiled as STORE_GLOBAL. After you do it, it's done. Use globals with care and the global keyword with greater care.
It is not possible to undo the effect of a global statement.
A global statement applies for the entire duration of the function in which it appears, regardless of where in the function it is, and regardless of whether it's executed. So, for example, in the assignment in the following function:
def f():
x = 3
if False:
global x
x is still treated as global.
So it wouldn't make sense to have another statement to undo its effect afterwards, since a global "statement" is not so much a statement, that is executed at some point during the function, as a declaration about the behavior of the function as a whole.