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.
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)
I have a global dictionary variable that will be used in a function that gets called multiple times. I don't have control of when the function is called, or a scope outside of the function I'm writing. I need to initialize the variable only if its not initialized. Once initialized, I will add values to it.
global dict
if dict is None:
dict = {}
dict[lldb.thread.GetThreadID()] = dict[lldb.thread.GetThreadID()] + 1
Unfortunately, I get
NameError: global name 'dict' is not defined
I understand that I should define the variable, but since this code is called multiple times, by just saying dict = {} I would be RE-defining the variable every time the code is called, unless I can somehow check if it's not defined, and only define it then.
Catching the error:
try:
_ = myDict
except NameError:
global myDict
myDict = {}
IMPORTANT NOTE:
Do NOT use dict or any other built-in type as a variable name.
A more idiomatic way to do this is to set the name ahead of time to a sentinel value and then check against that:
_my_dict = None
...
def increment_thing():
global _my_dict
if _my_dict is None:
_my_dict = {}
thread_id = lldb.thread.GetThreadID()
_my_dict[thread_id] = _my_dict.get(thread_id, 0) + 1
Note, I don't know anything about lldb -- but if it is using python threads, you might be better off using a threading.local:
import threading
# Thread local storage
_tls = threading.local()
def increment_thing():
counter = getattr(_tls, 'counter', 0)
_tls.counter = counter + 1
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
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
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.)