How do I set a global variable via function call? - python

I am trying to change the value of global variable edl_loading to True in function edl_flashing ,somehow it doesn't work?can anyone help understand why does print edl_loading prints False after call to edl_flashing in which I change the value to True
def edl_flashing():
edl_loading = True
print edl_loading
def main ():
global edl_loading
edl_loading = False
print edl_loading
edl_flashing()
print edl_loading #Why this prints as False
if __name__ == '__main__':
main()
OUTPUT:-
False
True
False

You need to use the global in both of your functions - main and edl_flashing
def edl_flashing():
global edl_loading
edl_loading = True
print edl_loading
Without the global declaration in the function, the variable name is local to the function.
The above change prints out
False
True
True

Related

How to change a global variable inside of two define's?

I want x to be equal to False. (Don't ask what's the purpose of the code, this is just an example.)
x = False
def first():
global x
x = True
def second():
if x == True:
x = False
#return?
first()
second()
print(x)
I have tried return, and defining x first as global

Python - Change a function parameter even if it's global

I've made a function that I want to use to change a variable, this variable also happens to be global.
def CheckMarkFunc(var):
if var == True:
var= False
elif var == False:
var= True
If var is a global, it wont change. Is there a way to change the var without having to hardcode the global parameter (sound_mute, in this case) into the function itself?
The code below works, but I'd rather not have multiple if statements for each global variable that I want to change, if at all possible:
def CheckMarkFunc(var,button_id,uncheck_texture,checked_texture):
global sound_mute
if var == True:
TextureSwap(uncheck_texture,button_id)
sound_mute = False
if var == False:
sound_mute = True
TextureSwap(checked_texture,button_id)
In both of these cases, the var parameter is the sound_mute boolean.
One option is as follows:
def CheckMarkFunc(var, button_id, uncheck_texture, checked_texture):
if var:
TextureSwap(uncheck_texture, button_id)
else:
TextureSwap(checked_texture, button_id)
return not var
sound_mute = CheckMarkFunc(sound_mute, button_id, uncheck_texture, checked_texture)

Changing values in decorator for nested functions

I have a case similar to this -
flag = True
print "Before All things happened, flag is", flag
def decorator(*a):
def real_decorator(function):
def wrapper(*args, **kwargs):
global flag
flag = False
print "just in real decorator before function call i.e. before", function.__name__
print "flag is " , flag
function(*args, **kwargs)
print "In real decorator after function call i.e. after", function.__name__
flag = True
print "flag is ", flag
return wrapper
return real_decorator
#decorator()
def subtota():
print "in subtota"
print "flag is" , flag
#decorator()
def print_args(*args):
print "in print args"
for arg in args:
print arg
print "flag is ", flag
subtota()
print "we do want flag to be false here, after subtota"
print "but, flag is ", flag
print_args("bilbo", "baggins")
print "after All things happended flag is ", flag
And the output is
Before All things happened, flag is True
just in real decorator before function call i.e. before print_args
flag is False
in print args
bilbo
baggins
flag is False
just in real decorator before function call i.e. before subtota
flag is False
in subtota
flag is False
In real decorator after function call i.e. after subtota
flag is True
we do want flag to be false here, after subtota
but, flag is True
In real decorator after function call i.e. after print_args
flag is True
after All things happended flag is True
Here, I do not want to change the value of flag after subtota() or may be we can say that, we want to keep behaviors of each function independent to each other.
How can we achieve this?
PS - Cannot avoid using Module-level global variable flag.
EDIT- desired behavior -
Only after the uppermost function is executed, the flag should be false.
I find it a little unclear as to what your goal is here.
If you need to track per-function state, you can set a flag on the decorated function object itself:
def decorator(*a):
def real_decorator(function):
def wrapper(*args, **kwargs):
function.flag = False
function(*args, **kwargs)
function.flag = True
return wrapper
return real_decorator
You could also set it on wrapper here to make the flag available on the decorated version:
wrapper.flag = False
If you need to toggle the flag only on entering and exiting the outermost decorated call, you could use a separate global to count how many levels in you are; you may as well set that on the decorator function:
def decorator(*a):
decorator._depth = 0
def real_decorator(function):
def wrapper(*args, **kwargs):
global flag
if decorator._depth == 0: # entering outermost call
flag = False
decorator._depth += 1
function(*args, **kwargs)
decorator._depth -= 1
if decorator._depth == 0: # exiting outermost call
flag = True
return wrapper
return real_decorator
Save the old value of flag inside wrapper, and restore to it instead of True
Apart from using variable which is scoped to the decorator, I tried using the following method-
def decorator(*a):
def real_decorator(function):
def wrapper(*args, **kwargs):
global flag
old_flag = flag
flag = False
function(*args, **kwargs)
flag = old_flag
return wrapper
return real_decorator
This seems a bit easy, and works perfectly fine.

Why won't a global variable change when assigning to it in a function?

I'm making a game in python, and I have some code set up as such:
istouching = False
death = True
def checkdead():
if istouching:
print "Is touching"
death = True
while death is False:
print death
# game logic
I know the game logic is working, because "Is touching" prints, but then when I print out the value of death, it remains false.
use global to change global variables inside a function, otherwise death=True inside checkdead() will actually define a new local variable.
def checkdead():
global death
if istouching == True: #use == here for comparison
print "Is touching"
death = True
Make checkdead return a value:
def checkdead():
if istouching:
print "Is touching"
return True
death = checkdead()
You could also use global, as #AshwiniChaudhar shows, but I think it is preferable to write functions that return values instead of functions that modify globals, since such functions can be unit-tested more easily, and it makes explicit what external variables are changed.
PS. if istouching = True should have resulted in a SyntaxError since you can not make a variable assignment inside a conditional expression.
Instead, use
if istouching:
That's scope-related.
death = False
def f():
death = True # Here python doesn't now death, so it creates a new, different variable
f()
print(death) # False
death = False
def f():
global death
death = True
f()
print(death) # True

Trouble with variable. [Python]

I have this variable on the beginning of the code:
enterActive = False
and then, in the end of it, I have this part:
def onKeyboardEvent(event):
if event.KeyID == 113: # F2
doLogin()
enterActive = True
if event.KeyID == 13: # ENTER
if enterActive == True:
m_lclick()
return True
hookManager.KeyDown = onKeyboardEvent
hookManager.HookKeyboard()
pythoncom.PumpMessages()
and I get this error when I press enter first, and when I press F2 first:
UnboundLocalError: local variable 'enterActive' referenced before assignment
I know why this happens, but I don't know how can I solve it...
anyone?
See Global variables in Python. Inside onKeyboardEvent, enterActive currently refers to a local variable, not the (global) variable you have defined outside the function. You need to put
global enterActive
at the beginning of the function to make enterActive refer to the global variable.
Approach 1: Use a local variable.
def onKeyboardEvent(event):
enterActive = false
...
Approach 2: Explicitly declare that you are using the global variable enterActive.
def onKeyboardEvent(event):
global enterActive
...
Because you have the line enterActive = True within the functiononKeyboardEvent, any reference to enterActive within the function uses the local variable by default, not the global one. In your case, the local variable is not defined at the time of its use, hence the error.
enterActive = False
def onKeyboardEvent(event):
global enterActive
...
Maybe you are trying to declare enterActive in another function and you aren't using the global statement to make it global. Anywhere in a function where you declare the variable, add:
global enterActive
That will declare it as global inside the functions.
Maybe this is the answer:
Using global variables in a function other than the one that created them
You are writing to a global variable and have to state that you know
what you're doing by adding a "global enterActive" in the beginning of
your function:
def onKeyboardEvent(event):
global enterActive
if event.KeyID == 113: # F2
doLogin()
enterActive = True
if event.KeyID == 13: # ENTER
if enterActive == True:
m_lclick()
return True

Categories