Below is my code
global PostgresDatabaseNameSchema
global RedShiftSchemaName
PostgresDatabaseNameSchema = None
RedShiftSchemaName = None
def check_assign_global_values():
if not PostgresDatabaseNameSchema:
PostgresDatabaseNameSchema = "Superman"
if not RedShiftSchemaName:
RedShiftSchemaName = "Ironman"
check_assign_global_values()
But i am getting an error saying
Traceback (most recent call last):
File "example.py", line 13, in <module>
check_assign_global_values()
File "example.py", line 8, in check_assign_global_values
if not PostgresDatabaseNameSchema:
UnboundLocalError: local variable 'PostgresDatabaseNameSchema' referenced before assignment
So can't we access or set the global variables from inside a function ?
global should always be defined inside a function, the reason for this is because it's telling the function that you wanted to use the global variable instead of local ones. You can do so like this:
PostgresDatabaseNameSchema = None
RedShiftSchemaName = None
def check_assign_global_values():
global PostgresDatabaseNameSchema, RedShiftSchemaName
if not PostgresDatabaseNameSchema:
PostgresDatabaseNameSchema = "Superman"
if not RedShiftSchemaName:
RedShiftSchemaName = "Ironman"
check_assign_global_values()
You should have some basic understanding of how to use global. There is many other SO questions out there you can search. Such as this question Using global variables in a function other than the one that created them.
Related
I have two blocks of python code, one works, and the other doesn't.
Working block:
env = {'user':'xyz'}
for key, value in env.items():
exec("{} = value".format(key))
print(user)
output:
xyz
The block, which doesn't work:
def test():
env = {'user':'xyz'}
for key, value in env.items():
exec("{} = value".format(key))
print(user)
test()
output:
NameError: name 'user' is not defined
The only difference I see is that the first block is being called in the global scope.
Could you please explain?
Many thanks!
PS: With all due respect, I know, I should avoid using exec() but what if I want to.
I recommend you reading this
You have to use locals() or exec or eval to access variables defined by exec in a function in Python3.
def test():
env = {'user': 'xyz'}
for key, value in env.items():
exec("{} = value".format(key))
exec("print(user)")
print(locals()['user'])
print(eval("user"))
test()
It should be noted that, if you attempt to store value returned from eval. You will get NameError.
def test():
env = {'user': 'xyz'}
for key, value in env.items():
exec("{} = value".format(key))
user = eval("user")
print(user)
test()
returns
Traceback (most recent call last):
File "D:/Git/sscgc/test.py", line 8, in <module>
test()
File "D:/Git/sscgc/test.py", line 5, in test
user = eval("user")
File "<string>", line 1, in <module>
NameError: name 'user' is not defined
I am new in Python and I get these errors when running this Python class:
I am using PyScripter and I am running Python 3.9 (64-bit)
I created the class Heater, initialized a variable temperature, and some functions that modifies this variable.
Then I created an object and used the functions then it gave me an Error!
class Heater :
temperature = 0
def __init__(self):
temperature = 20
def warmer(self):
temperature += 5
def cooler(self):
temperature -= 5
def display(self):
print ("Temperature is " , self.temperature)
h1 = Heater()
h1.display()
h1.cooler()
h1.display()
h1.warmer()
h1.display()
I am getting the following Output and then this Error:
Temperature is 0
Traceback (most recent call last):
File "<module1>", line 30, in <module>
File "<module1>", line 22, in cooler
UnboundLocalError: local variable 'temperature' referenced before assignment
I changed temperature = 0 into nonlocal temperature then I get this error:
File "<module1>", line 13
SyntaxError: no binding for nonlocal 'temperature' found
After looking at your code, I noticed that you are trying to access self.temperature using just temperature.
The first argument each method receives (self) is a reference of the object itself, and is used to access object attributes and methods.
I'm invoking one function using a button click. But it is giving me error: NameError: global name 'new' is not defined ,even though I have defined new as a new window.
My code for a new window:
def result():
root.withdraw()
new = Toplevel()
new.geometry("1105x605+300+300")
button3 = Button(new, text='Select a Query Image',command = matching_image)
button3.pack(padx = 1, pady = 1,anchor='ne')
button3.place( x = 570, y = 60)
The button will invoke matching_image function, and the code will be:
def matching_image():
path1 = tkFileDialog.askopenfilename(filetypes=[("Image File",'.jpg')])
im = Image.open(path1)
resized = im.resize((200, 200),Image.ANTIALIAS)
tkimage = ImageTk.PhotoImage(resized)
myvar1 = Label(new,image = tkimage)
myvar1.image = tkimage
myvar1.pack()
myvar1.place(x = 30, y = 100)
And this is giving the error. The error message is as follows:
%run "D:/6th sem/Major project/Code/frame.py"
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\Enthought\Canopy32\App\appdata\canopy-1.0.3.1262.win-x86\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "D:\6th sem\Major project\Code\frame.py", line 194, in matching_image
myvar1 = Label(new,image = tkimage)
NameError: global name 'new' is not defined
Any suggestions! So that I can solve this error.
Thanks in advance :)
You defined new in a function, so that variable only exists in that function's scope. Therefore, when you try to access it in another scope (here it is the global scope) you will get a NameError as it is not available at that level.
You can fix this by doing global new at the start of the function in which you define it.
This statement puts it in the global scope, meaning that it is defined at the module level. Therefore, you can access it anywhere in the program and you will not get that error.
Like this:
def result():
global new
new = Toplevel()
# Other stuff.
Though note that doing global declarations is considered bad practice. Much better to put your code in class form and assign applicable variables to self.
Your problem is condensed down to this:
def foo():
var = 1
def bar():
print var
foo()
bar()
The principle problem you have is that 'var' is a local, not a global.
This code example works:
def foo():
global var
var = 1
def bar():
print var
foo()
bar()
Because var is declared to be global instead.
def buy():
while True:
items={"Armor": 25, "Sword": 25}
print("What do you want to buy?\n1/Armor +25 defense\t50 golds\n2/Sword +25 damage\t50 golds")
s1=input("Choose the item you want to buy (1 and/or 2 only): ")
try:
global a
a=int(s1)
if a in range (1,3):
break
except ValueError:
pass
buy()
print(a)
error message:
Traceback (most recent call last):
File "C:\code\work\The Role-Playing combat game.py", line 58, in <module>
print(a) NameError: global name 'a' is not defined
Line 58 is print(a)
I declared "a" as the global value, but somehow the interpreter gives me the error message. Please help, thanks.
Solved, declare "a" outside of the function first
Did you declare the a variable earlier in your code? Otherwise, calling global a before declaring it will throw that error. You need to put a = something before you call global a on it.
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