Is it possible to pass global variables through a function. For example
def start():
global var
if var == 0:
print("Error")
else:
while var> -1:
print(var)
var = var - 1
Your start function explicitly allows access to a global variable named var. As evidenced by your error, you have no such variable defined. Please initialize the variable before the function:
var = 25
def start():
global var
# the rest of your function
# goes here after global var
Related
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)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Short Description of Python Scoping Rules
I wrote two simple functions:
# coding: utf-8
def test():
var = 1
def print_var():
print var
print_var()
print var
test()
# 1
# 1
def test1():
var = 2
def print_var():
print var
var = 3
print_var()
print var
test1()
# raise Exception
In comparison, test1() assigns value after print var, then raise an Exception: UnboundLocalError: local variable 'var' referenced before assignment, I think the moment I call inner print var, var has a value of 2, am I wrong?
Yes, you're incorrect here. Function definition introduces a new scope.
# coding: utf-8
def test():
var = 1
def print_var():
print var <--- var is not in local scope, the var from outer scope gets used
print_var()
print var
test()
# 1
# 1
def test1():
var = 2
def print_var():
print var <---- var is in local scope, but not defined yet, ouch
var = 3
print_var()
print var
test1()
# raise Exception
Could I set a variable inside a function scope, knowing that I sent this variable like a parameter..
See the example:
def test(param):
param = 3
var = 5
test(var)
print var
I want the value printed be 3, but it doesn't happen.
How can I do that?
Thanks..
You can return the value of param like this:
def test(param)
param = 3
return param
var = 5
var = test(var)
Or you can use a global variable.
Better to use return than a global:
def test(param):
param = 3
return param
var = 5
var = test(var)
print var
The global statement allows you to assign to variables declared outside a function's scope.
var = 5
def test():
global var
var = 3
test()
print var
However, I have found that I seldom need to use this technique. The functional programming model makes this less important.
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
Let's say we have a module m:
var = None
def get_var():
return var
def set_var(v):
var = v
This will not work as expected, because set_var() will not store v in the module-wide var. It will create a local variable var instead.
So I need a way of referring the module m from within set_var(), which itself is a member of module m. How should I do this?
def set_var(v):
global var
var = v
The global keyword will allow you to change global variables from within in a function.
As Jeffrey Aylesworth's answer shows, you don't actually need a reference to the local module to achieve the OP's aim. The global keyword can achieve this aim.
However for the sake of answering the OP title, How to refer to the local module in Python?:
import sys
var = None
def set_var(v):
sys.modules[__name__].var = v
def get_var():
return var
As a follow up to Jeffrey's answer, I would like to add that, in Python 3, you can more generally access a variable from the closest enclosing scope:
def set_local_var():
var = None
def set_var(v):
nonlocal var
var = v
return (var, set_var)
# Test:
(my_var, my_set) = set_local_var()
print my_var # None
my_set(3)
print my_var # Should now be 3
(Caveat: I have not tested this, as I don't have Python 3.)