Python scope: "UnboundLocalError: local variable 'c' referenced before assignment" [duplicate]
I am trying to figure out this:
c = 1
def f(n):
print c + n
def g(n):
c = c + n
f(1) # => 2
g(1) # => UnboundLocalError: local variable 'c' referenced before assignment
Thanks!
Asked by: John467 | Posted: 28-01-2022
Answer 1
Within a function, variables that are assigned to are treated as local variables by default. To assign to global variables, use the global
statement:
def g(n):
global c
c = c + n
This is one of the quirky areas of Python that has never really sat well with me.
Answered by: Lily258 | Posted: 01-03-2022Answer 2
Global state is something to avoid, especially needing to mutate it. Consider if g()
should simply take two parameters or if f()
and g()
need to be methods of a common class with c
an instance attribute
class A:
c = 1
def f(self, n):
print self.c + n
def g(self, n):
self.c += n
a = A()
a.f(1)
a.g(1)
a.f(1)
Outputs:
2
3
Answered by: Rafael951 | Posted: 01-03-2022
Answer 3
Errata for Greg's post:
There should be no before they are referenced. Take a look:
x = 1
def explode():
print x # raises UnboundLocalError here
x = 2
It explodes, even if x is assigned after it's referenced. In Python variable can be local or refer outer scope, and it cannot change in one function.
Answered by: Brooke444 | Posted: 01-03-2022Answer 4
Other than what Greg said, in Python 3.0, there will be the nonlocal statement to state "here are some names that are defined in the enclosing scope". Unlike global those names have to be already defined outside the current scope. It will be easy to track down names and variables. Nowadays you can't be sure where "globals something" is exactly defined.
Answered by: Emma142 | Posted: 01-03-2022Similar questions
numpy - Help with Python UnboundLocalError: local variable referenced before assignment
I have post the similar question before,however,I think I may have misinterpreted my question,so may I just post my origin code here,and looking for someone can help me,I am really stuck now..thanks alot.
from numpy import *
import math as M
#initial condition All in SI unit
G=6.673*10**-11 #Gravitational constant
ms=1.9889*10**30 #mass of the sun
me=5.9742*10**24 #mass of the earth
dt=10 #tim...
python - UnboundLocalError: local variable 'conn' referenced before assignment
This question already has answers here:
python - UnboundLocalError: local variable 'items' referenced before assignment
This question already has answers here:
python - Reused variable in Mako template cause "UnboundLocalError: local variable 'xyz' referenced before assignment"
I have this "funny" issue. I know this error message is found in a lot of places, but I couldn't find one explicitely related to Mako.
In a Mako template, I have (snippet):
<%inherit file="other.mako"/>
<%def name="my_method()">Search for ${label}</%def>
[...]
<h2>${label.capitalize()} found: ${len(l)}</h2>
...
<ol>
% for (label, field_name) in some_list:
<li>${label}: ${fie...
python - UnboundLocalError: local variable 'x' referenced before assignment
I am trying to execute this code,
import osgeo.ogr
def findPoints(geometry, results):
for i in range(geometry.GetPointCount()):
x,y,z = geometry.GetPoint(i)
if results['north'] == None or results['north'][1] < y:
results['north'] = (x,y)
if results['south'] == None or results['south'][1] > y:
results['south'] = (x,y)
for i in range(geometry.GetGeometryCount()):...
python - UnboundLocalError: local variable "xyz" referenced before assignment
UPDATE: In response to Wooble's comment, adding a "sector = None" before the for simply returns "None". I think the issue is that the variable in the for loop is not being returned.
The following is part of a function that was running fine, until recently, when I changed a seemingly unrelated part of the code.
#--> the only part I had changed recently was adding "stockurl" to the re...
python: UnboundLocalError: local variable 'open' referenced before assignment
def read_lines():
readFileName = "readfile.txt"
f = open(readFileName, 'r+')
contents = f.read()
... # and so on
read_lines()
When I run this, I get an error:
f = open(readFileName, 'r+')
UnboundLocalError: local variable 'open' referenced before assignment
python - Receiving : "UnboundLocalError: local variable referenced before assignment"
I have seen multiple threads with people having the same problem, but it seems solutions have been offered on a case-by-case basis due to the unique nature of the problem
Here's my code:
loga = [(912, "Message A1") , (1000, "Message A2") , (988, "Message A3") , (1012, "Message A4") , (1002, "Message A5")]
logb = [(926, "Message B1") , (1008, "Message B2") , (996, "Message B3") , (1019, "Message B4")...
python - UnboundLocalError: local variable 'print' referenced before assignment
Closed. This question is not reproducible or was caused...
python - "UnboundLocalError: local variable referenced before assignment" after an if statement
I have also tried searching for the answer but I don't understand the answers to other people's similar problems...
tfile= open("/home/path/to/file",'r')
def temp_sky(lreq, breq):
for line in tfile:
data = line.split()
if ( abs(float(data[0]) - lreq) <= 0.1
and abs(float(data[1]) - breq) <= 0.1):
T= data[2]
return T
print temp_sky(60, 6...
python - UnboundLocalError: local variable 'r' referenced before assignment
This question already has answers here:
python - UnboundLocalError: local variable 'a' referenced before assignment
This question already has answers here:
python - UnboundLocalError: local variable referenced before assignment issue
class Factor:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def commonFactor(self):
global cfa
cfa = self.a
cfb = self.b
while cfb: ...
python - Error Code: UnboundLocalError: local variable referenced before assignment
It seems that many get this error but each situation is different.
My code:
i = 0
def sort(a):
b = len(a)
if(i == b):
print (a)
elif(b == 0):
print ('Error. No value detected...')
elif(b == 1):
print (a)
elif(a[i]>a[i+1]):
a[i], a[i+1] = a[i+1], a[i]
i = i + 1
print(a)
sort(a)
Error Code:
python - UnboundLocalError: local variable 'gold' referenced before assignment
This question already has answers here:
python - Another UnboundLocalError: local variable referenced before assignment Issue
I stumbled upon a situation that shutters my understanding of Pythons variable scope.
Here is the code:
transaction_id = None
def parseFileContent(hostID,marketID, content, writeToDB=False):
features = _buildObjects(StringIO.StringIO(content))
for feature in features:
featureID = adapter.addFeature(feature.name,boris)
print transaction_id #breaks here UnboundLocalError:...
python - python2.7 error: UnboundLocalError: local variable 'i' referenced before assignment
I get an error when I run this python script.
def thousandthPrime():
count=0
candidate=5 #candidates for prime no. these are all odd no.s Since starts at 5 therefore we find 998th prime no. as 2 and 3 are already prime no.s
while(True):
#print 'Checking =',candidate
for i in range(2,candidate/2): #if any number from 2 to candidate/2 can divide candidate with remainder = 0 then c...
python - "UnboundLocalError: local variable 'input' referenced before assignment"
When I run my code I get these errors:
linechoice = input("What password do you want to delete?:\n")
UnboundLocalError: local variable 'input' referenced before assignment
def delete():
print("Welcome to the password delete system.")
file = open("pypyth.txt", "w")
output = []
linechoice = input("What password do you want to dele...
UnboundLocalError: local variable 'L' referenced before assignment Python
This question already has answers here:
python - UnboundLocalError: local variable referenced before assignment using csv file
Making a currency converter but i have an error, firstly prints
sorry not a valid currency
after
Pound Sterling
Please enter the amount of money to convert: 100
['Pound Sterling', 'Euro', 'US Dollar', 'Japanese Yen']
Please enter the current currency: 'Euro'
1.22
Please enter the currency you would like to convert to: 'Pound Sterling'
Sorry, that is not a valid currency
...
numpy - Help with Python UnboundLocalError: local variable referenced before assignment
I have post the similar question before,however,I think I may have misinterpreted my question,so may I just post my origin code here,and looking for someone can help me,I am really stuck now..thanks alot.
from numpy import *
import math as M
#initial condition All in SI unit
G=6.673*10**-11 #Gravitational constant
ms=1.9889*10**30 #mass of the sun
me=5.9742*10**24 #mass of the earth
dt=10 #tim...
python - UnboundLocalError: local variable 'conn' referenced before assignment
This question already has answers here:
python - UnboundLocalError: local variable 'items' referenced before assignment
This question already has answers here:
python - Reused variable in Mako template cause "UnboundLocalError: local variable 'xyz' referenced before assignment"
I have this "funny" issue. I know this error message is found in a lot of places, but I couldn't find one explicitely related to Mako.
In a Mako template, I have (snippet):
<%inherit file="other.mako"/>
<%def name="my_method()">Search for ${label}</%def>
[...]
<h2>${label.capitalize()} found: ${len(l)}</h2>
...
<ol>
% for (label, field_name) in some_list:
<li>${label}: ${fie...
python - UnboundLocalError: local variable 'x' referenced before assignment
I am trying to execute this code,
import osgeo.ogr
def findPoints(geometry, results):
for i in range(geometry.GetPointCount()):
x,y,z = geometry.GetPoint(i)
if results['north'] == None or results['north'][1] < y:
results['north'] = (x,y)
if results['south'] == None or results['south'][1] > y:
results['south'] = (x,y)
for i in range(geometry.GetGeometryCount()):...
python - UnboundLocalError: local variable "xyz" referenced before assignment
UPDATE: In response to Wooble's comment, adding a "sector = None" before the for simply returns "None". I think the issue is that the variable in the for loop is not being returned.
The following is part of a function that was running fine, until recently, when I changed a seemingly unrelated part of the code.
#--> the only part I had changed recently was adding "stockurl" to the re...
python: UnboundLocalError: local variable 'open' referenced before assignment
def read_lines():
readFileName = "readfile.txt"
f = open(readFileName, 'r+')
contents = f.read()
... # and so on
read_lines()
When I run this, I get an error:
f = open(readFileName, 'r+')
UnboundLocalError: local variable 'open' referenced before assignment
python - Receiving : "UnboundLocalError: local variable referenced before assignment"
I have seen multiple threads with people having the same problem, but it seems solutions have been offered on a case-by-case basis due to the unique nature of the problem
Here's my code:
loga = [(912, "Message A1") , (1000, "Message A2") , (988, "Message A3") , (1012, "Message A4") , (1002, "Message A5")]
logb = [(926, "Message B1") , (1008, "Message B2") , (996, "Message B3") , (1019, "Message B4")...
python - UnboundLocalError: local variable 'print' referenced before assignment
Closed. This question is not reproducible or was caused...
python - "UnboundLocalError: local variable referenced before assignment" after an if statement
I have also tried searching for the answer but I don't understand the answers to other people's similar problems...
tfile= open("/home/path/to/file",'r')
def temp_sky(lreq, breq):
for line in tfile:
data = line.split()
if ( abs(float(data[0]) - lreq) <= 0.1
and abs(float(data[1]) - breq) <= 0.1):
T= data[2]
return T
print temp_sky(60, 6...
numpy - Help with Python UnboundLocalError: local variable referenced before assignment
I have post the similar question before,however,I think I may have misinterpreted my question,so may I just post my origin code here,and looking for someone can help me,I am really stuck now..thanks alot.
from numpy import *
import math as M
#initial condition All in SI unit
G=6.673*10**-11 #Gravitational constant
ms=1.9889*10**30 #mass of the sun
me=5.9742*10**24 #mass of the earth
dt=10 #tim...
multithreading - Python: Help with UnboundLocalError: local variable referenced before assignment
I keep getting this error for a portion of my code.
Traceback (most recent call last):
File "./mang.py", line 1688, in <module>
files, tsize = logger()
File "./mang.py", line 1466, in logger
nl = sshfile(list, "nl")
UnboundLocalError: local variable 'sshfile' referenced before assignment
I haven't put the code up cause it goes back and forth between functions. I'm wondering if anyone...
python - UnboundLocalError: Decorator with default parameters
Here is my decorator code. I'm getting UnboundLocalError for some reason but I couldn't find it.
>>> def validate(schema=None):
def wrap(f):
def _f(*args, **kwargs):
if not schema:
schema = f.__name__
print schema
return f()
return _f
return wrap
>>> @validate()
def some_function():
...
python - UnboundLocalError: local variable 'prod_Available' referenced before assignment
I am developing a reservation system, and i have a function that save the quantity of a product... My question is why I got this problem ? when i
`curl -l -X POST -d "product=3&client=1&function=insert_booking&check_in=2011-12-15&check_out=2011-12-10&no_of_adult=2&no_of_kid=1&quantity=2&first_name=asda&last_name=sdsd&contact=34343" http://127.0.0.1:8000/api/reserve`
...
python - UnboundLocalError: local variable 'conn' referenced before assignment
This question already has answers here:
python - UnboundLocalError: local variable 'items' referenced before assignment
This question already has answers here:
python - Reused variable in Mako template cause "UnboundLocalError: local variable 'xyz' referenced before assignment"
I have this "funny" issue. I know this error message is found in a lot of places, but I couldn't find one explicitely related to Mako.
In a Mako template, I have (snippet):
<%inherit file="other.mako"/>
<%def name="my_method()">Search for ${label}</%def>
[...]
<h2>${label.capitalize()} found: ${len(l)}</h2>
...
<ol>
% for (label, field_name) in some_list:
<li>${label}: ${fie...
python - UnboundLocalError: local variable 'x' referenced before assignment
I am trying to execute this code,
import osgeo.ogr
def findPoints(geometry, results):
for i in range(geometry.GetPointCount()):
x,y,z = geometry.GetPoint(i)
if results['north'] == None or results['north'][1] < y:
results['north'] = (x,y)
if results['south'] == None or results['south'][1] > y:
results['south'] = (x,y)
for i in range(geometry.GetGeometryCount()):...
python - UnboundLocalError: local variable 'full_path' referenced before assignment
Using Window 7 64Bit with Python 2.7 and Django 1.4.
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Django-1.4\django\bin\cms2>manage.py syncdb
Creating tables ...
Installing custom SQL ...
Installing indexes ...
Traceback (most recent call last):
File "C:\Django-1.4\django\bin\cms2\manage.py", line 10, in <module>
execute_from_command...
python - uwsgi, gevent and async loops - UnboundLocalError: local variable 'query_string' referenced before assignment
My stack is the uWSGI 1.2.2, bottle, and gevent 1.0b2. I am trying to do the following async.
1) serve a pixel image as fast as possible and close the connection
2) I then pass the query string to a function so I can use gevent to async write data to redis
3) Per the uwsgi doc at http://projects.unbit.it/uwsgi/wiki/Gevent I appear to doing it...
Still can't find your answer? Check out these communities...
PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python