python err: Local variable referenced before assignment - python

I get error UnboundLocal: Local variable T referenced before assignment, however it's not like that:
import ...
T = 0
def do_something():
do_something_else(T) # err at this line
T += 1
def do_something_else(t):
print t
do_something()
That is how my code looks, so it is not reference before assignment. (correct me if I am wrong) What's wrong?

Declare T as global variable:
def do_something():
global T # <--------------
do_something_else(T) # err at this line
T += 1

Related

Python UnboundLocalError, what causes it?

In python I wrote:
registered_to = 0
def execute_data():
registered_to += response.text.count("<div class=\"info-msg\">")
But I'm getting:
registered_to += response.text.count("<div class=\"info-msg\">")
UnboundLocalError: local variable 'registered_to' referenced before assignment
Is this what you want?
registered_to = 0
def execute_data():
global registered_to
registered_to += response.text.count("<div class=\"info-msg\">")
global keyword must be used whenever you wish to modify/create global variables from a non-global scope like a function. If you are just using a global variable from a non-global scope and not modifying it, you need not use the keyword.
Examples
Using global variable in a non-global scope but not modifying it
wish = "Hello "
def fun():
print(wish)
fun()
Using global variable in a non-global scope and modifying it as well
wish = "Hello "
def fun():
word += "World"
print(wish)
fun()

NameError: name 'acc' is not defined in pyspark accumulator

Test Accumulator in pyspark but it went wrong:
def test():
conf = SparkConf().setAppName("test").setMaster("local[*]")
sc = SparkContext(conf=conf).getOrCreate()
rdds = sc.parallelize([Row(user="spark", item="book"), Row(user="spark", item="goods"),
Row(user="hadoop", item="book"), Row(user="python", item="duck")])
acc = sc.accumulator(0)
print("accumulator: {}".format(acc))
def imap(row):
global acc
acc += 1
return row
rdds.map(imap).foreach(print)
print(acc.value)
The error is:
...
return f(*args, **kwargs)
File "test_als1.py", line 205, in imap
acc += 1
NameError: name 'acc' is not defined
But I set the acc as global variable, how can I write the code?
The problem is that imap is referencing a global variable that doesn't exist (the assignment in test only creates a local variable in that function). This simple program (without Spark) fails with the same error for the same reason:
def foo():
blah = 1
def bar():
global blah
print(blah)
bar()
if __name__ == '__main__':
foo()
Assigning acc at the module level works:
if __name__ == '__main__':
conf = SparkConf().setAppName("test").setMaster("local[*]")
sc = SparkContext(conf=conf).getOrCreate()
rdds = sc.parallelize([Row(user="spark", item="book"), Row(user="spark", item="goods"),
Row(user="hadoop", item="book"), Row(user="python", item="duck")])
acc = sc.accumulator(0)
print("accumulator: {}".format(acc))
def imap(row):
global acc
acc += 1
return row
rdds.map(imap).foreach(print)
print(acc.value)
Adding a global acc statement to test is an alternative if you need to keep the function test.
Just remove this line
global acc
global is used to access the globally declared variable but your variable is declared inside a function and you can directly access it inside your nested imap function.
For more example of global visit here.

UnboundLocalError error: local variable 'i' referenced before assignment

I'm writing a program in selenium python. I pasted here part of the code from my program (I did not paste all the code because it has 800 lines) with the UnboundLocalError error: local variable 'i' referenced before assignment, the error occurs exactly at i += 1.
global i
i = 0
odpowiadanieobserwowaniestronfb0()
def odpowiadanieobserwowaniestronfb0():
if i > ileraz:
driver.quit
skonczono()
'''
try:
testt = driver.find_element_by_xpath('')
except Exception:
odpowiadanieobserwowaniestronfb1()
zleskonczono1()
'''
def odpowiadanieobserwowaniestronfb1():
i += 1
global keyword tells the function, not the whole module / file, what variables should be considered declared outside the scope of the said function. Try this:
def odpowiadanieobserwowaniestronfb1():
global i
i += 1
There are two options:
You can use your global variable:
def odpowiadanieobserwowaniestronfb1():
global i
i += 1
or you pass the i to the function:
def odpowiadanieobserwowaniestronfb1( i ):
return i += 1

Using variables from another function in a function

I have tried to search this but I don't quite understand. I am coming across this error so I formed a quick easy example.
def test():
global a
a = 0
a+=1
def test2():
a+=1
print (a)
inp = input('a?')
if inp == 'a':
test()
test2()
When I input a. I expected the code to output 2. However, I get this error UnboundLocalError: local variable 'a' referenced before assignment. When I searched around about this, I found that you need to use global, but I already am using it.
So I don't understand. Can someone briefly explain what I'm doing wrong?
Thanks.
A global declaration only applies within that function. So the declaration in test() means that uses of the variable a in that function will refer to the global variable. It doesn't have any effect on other functions, so if test2 also wants to access the global variable, you need the same declaration there as well.
def test2():
global a
a += 1
print(a)
1) You can return the modified value like:
def test():
a = 0
a+=1
return a
def test2(a):
a+=1
print (a)
inp = input('a?')
if inp == 'a':
a = test()
test2(a)
2) Or you can use a class:
class TestClass:
a = 0
def test(self):
self.a = 0
self.a+=1
def test2(self):
self.a+=1
print (self.a)
Usage of option 2:
>>> example = TestClass()
>>> example.test()
>>> example.test2()
2

Unbound Local Error with global variable [duplicate]

This question already has answers here:
Using global variables in a function
(25 answers)
Closed 7 months ago.
I am trying to figure out why I get an UnboundLocalError in my pygame application, Table Wars. Here is a summary of what happens:
The variables, REDGOLD, REDCOMMAND, BLUEGOLD and BLUECOMMAND, are initialised as global variables:
#Red Stat Section
REDGOLD = 50
REDCOMMAND = 100
#Blue Stat Section
BLUEGOLD = 50
BLUECOMMAND = 100
def main():
[...]
global REDGOLD
global REDCOMMAND
global BLUEGOLD
global BLUECOMMAND
This works when spawning units within the main loop, subtracting funds to spawn units.
Right now, I am trying to set up a system so that when a unit dies, the killer refunds the victim's COMMAND and earns GOLD based on what he killed:
class Red_Infantry(pygame.sprite.Sprite):
def __init__(self, screen):
[...]
self.reward = 15
self.cmdback = 5
[...]
def attack(self):
if self.target is None: return
if self.target.health <= 0:
REDGOLD += self.target.reward #These are the problem lines
BLUECOMMAND += self.target.cmdback #They will cause the UnboundLocalError
#when performed
self.target = None
if not self.cooldown_ready(): return
self.target.health -= self.attack_damage
print "Target's health: %d" % self.target.health
This works right up until the unit dies. Then this happens:
Traceback (most recent call last):
File "C:\Users\Oventoaster\Desktop\Games\Table Wars\Table Wars.py", line 606, in <module>
main()
File "C:\Users\Oventoaster\Desktop\Games\Table Wars\Table Wars.py", line 123, in main
RedTeam.update()
File "C:\Python27\lib\site-packages\pygame\sprite.py", line 399, in update
for s in self.sprites(): s.update(*args)
File "C:\Users\Oventoaster\Desktop\Games\Table Wars\Table Wars.py", line 304, in update
self.attack()
File "C:\Users\Oventoaster\Desktop\Games\Table Wars\Table Wars.py", line 320, in attack
REDGOLD += self.target.reward
UnboundLocalError: local variable 'REDGOLD' referenced before assignment
How do I get the global variables mentioned above to change with the attack block? If it helps, I am using Pygame 2.7.x, so nonlocal won't work :/
global make the global variable visible in the current code block. You only put the global statement in main, not in attack.
ADDENDUM
Here is an illustration of the need to use global more than once. Try this:
RED=1
def main():
global RED
RED += 1
print RED
f()
def f():
#global RED
RED += 1
print RED
main()
You will get the error UnboundLocalError: local variable 'RED' referenced before assignment.
Now uncomment the global statement in f and it will work.
The global declaration is active in a LEXICAL, not a DYNAMIC scope.
You need to declare the variable as global in each scope where they are being modified
Better yet find a way to not use globals. Does it make sense for those to be class attributes for example?
Found that variables in main act like global "read only" variables in function. If we try to reassign the value, it will generate error.
Try:
#!/usr/bin/env python
RED=1
A=[1,2,3,4,5,6]
def f():
print A[RED]
f()
It's ok.
But:
#!/usr/bin/env python
RED=1
A=[1,2,3,4,5,6]
def f():
print A[RED]
A = [1,1,1,1,1]
f()
Generate
File "./test.py", line 6, in f
print A[RED]
UnboundLocalError: local variable **'A'** referenced before assignment
and:
#!/usr/bin/env python
RED=1
A=[1,2,3,4,5,6]
def f():
print A[RED]
RED = 2
f()
Generate
File "./test.py", line 6, in f
print A[RED]
UnboundLocalError: local variable **'RED'** referenced before assignment

Categories

Resources