How do I get global variables in Python? [duplicate] - python

This question already has answers here:
How can I access global variable inside class in Python
(6 answers)
Closed 8 years ago.
Right, so I'm making a program...
def aFunction():
aVariable = 5
aVariable = 9
aFunction()
...and of course this won't work. What I am trying to do is to make aVariable changeable in other functions, namely, aFunction. How do I do that? Can I use the global statement, I have heard some bad things about it, although I don't really remember why?

You should use global:
def aFunction():
global aVariable
aVariable = 5
aVariable = 9
aFunction()
print aVariable #print 5

So this is a comprehensive explanation why global variables are bad in every programming language: global variables are bad
For your problem, you can use return values, for example:
def a_function(a_variable):
return a_variable - 5
a_variable = 9
a_variable = a_function(a_variable)

Related

Why does the method what_are_you output nothing? Syntax mistake? [duplicate]

This question already has answers here:
What is the purpose of the `self` parameter? Why is it needed?
(26 answers)
Closed 3 years ago.
In this program the output is not what I would expect:
class example(object):
def __init__(self, foo,bar):
self.foo = foo
self.bar = bar
def what_are_you():
print(foo,bar)
print("This doesn't work either")
a = example("aaa","bbb")
a.what_are_you
#should return "aaa bbb"
print(a.what_are_you)
print(a.foo,a.bar)
Instead it outputs nothing. This is the whole output:
<bound method example.what_are_you of <__main__.example object at 0x000002A9574B4710>>
aaa bbb
Process returned 0 (0x0) execution time : 0.041 s
By not including parentheses, you're printing the function object, not calling the function. To call the function, put parentheses after it.
print(a.what_are_you())
will print the value of what_are_you() (whatever is in the return statement)
As I see now, you're printing stuff, not returning stuff, so you might need to use:
a.what_are_you()
And in your function, you need to use self to get the variable:
def what_are_you(self):
print(self.foo,self.bar)
print("This doesn't work either")

Python how to change "existing" variable [duplicate]

This question already has answers here:
Global Variable in Python
(2 answers)
Closed 5 years ago.
I have a little python application, and declared at the top of the application a string called lastMsg, in a function, this string should be changed, but instead of changing the existing string, it creates a new string, how can I change the old string?
If I guessed correctly what you are trying to do (do share some code to further explain your answer):
You need to use the global keyword to specify you want to change the global variable.
myVar = "1"
def myFun():
global myVar
myVar = "2"
print(myVar)
myFun()
print(myVar)
Should print:
1
2
It's not quite clear what you're asking.
I think you mean this:
lastMsg = "some string"
def a_function():
lastMsg = "new value"
If so, you can change it using the global keyword:
lastMsg = "some string"
def a_function():
global lastMsg
lastMsg = "new value"

Python: modify global var from a function argument [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
How do I get a result (output) from a function? How can I use the result later?
(4 answers)
Closed 7 months ago.
I'd like to create a function that will modify an initialized global variable based on the argument passed to it, but I get a SyntaxError: name 'arg' is local and global. I have seen other methods to accomplish this, using globals() or creating a simple func inside myFunc to "trick" Python. Another approach would be to create if statements inside myFunc to explicitly assign the corresponding global variables, but that seems overly verbose.
Why does this occur, and what would be the most efficient/elegant/Pythonic way to accomplish this?
Given:
var1 = 1
var2 = 2
var3 = 3
def myFunc(arg):
global arg
arg = 10
myFunc(var1) # each of these should print to 10
myFunc(var2)
myFunc(var3)
You can use globals() to access the variables and assign new values from within myFunc()
var1 = 1
var2 = 2
def myFunc(varname):
globals()[varname] = 10
print(var1, var2)
myFunc("var1")
myFunc("var2")
print(var1, var2)
Will output:
1, 2
10, 10
In python a variable is a name for an object. When you call a function, and pass it an argument you're passing the object associated with the variable, not the name. So for example when you call wash(mydog), you're saying "wash the object known as mydog". Keep in mind, that the same object could have more than one name, for example spot = mydog = best_dog_ever = new_dog(). The function doesn't know which name was used to pass it the object, and even if it did, what if the name used was not the one in the global scope, you'd have to have some way of saying this function only takes global variables as arguments.
I hope that helps explain why you're getting a syntax error, but you can still accomplish pretty much the same thing at least two ways. The first is to simply assign the return value to the variable you're trying to change, for example:
var1 = 1
var2 = 2
def addone(a):
return a + 1
def main():
global var1, var2
var1 = addone(var1)
var2 = addone(var2)
print var1, var2
main()
print var1, var2
The second is to use a more object oriented approach, something like this:
class GlobalValue(object):
def __init__(self, value):
self.value = value
var1 = GlobalValue(1)
var2 = GlobalValue(2)
def addone(a):
a.value += 1
print var1.value, var2.value
addone(var1)
addone(var2)
print var1.value, var2.value
Or even better:
class GlobalValue(object):
def __init__(self, value):
self.value = value
def addone(self):
self.value += 1
var1 = GlobalValue(1)
var2 = GlobalValue(2)
print var1.value, var2.value
var1.addone()
var2.addone()
print var1.value, var2.value
Why does this occur
Because the global variable that you want to use has the same name as the parameter, arg. In Python, parameters are local variables, and a variable can only be local or global, not both.
It appears as though you expected to be able to use the contents of var to, somehow, specify which existing global variable to modify. It does not work like that. First off, variables don't contain other variables; they contain values. The name of a variable isn't a value. Again, parameters are local variables - and calling a function assigns to those variables. It assigns a value. (Keep in mind that you could just as easily call the function without a variable for the argument: myFunc(3). Should this cause 3 to become equal to 10 somehow?)
Second, even if you passed, for example, a string, you would have to do more work in order to access the corresponding global variable. It can be done, but please do not.
and what would be the most efficient/elegant/Pythonic way to accomplish this?
The Pythonic way is don't. If you want your function to communicate information out when it is called, return a value:
def myFunc():
return 10
var1 = myFunc()
var2 = myFunc()
var3 = myFunc()
The simplest way to fix the error is to just rename the global variable. However, this does not fix the apparent intent of the code:
var1 = 1
var2 = 2
var3 = 3
def myFunc(arg):
global g
g = 10
# var1, var2 and var3 will NOT CHANGE
# Instead, the new global variable g is created, and assigned a value of 10,
# three times in a row.
myFunc(var1)
myFunc(var2)
myFunc(var3)

Order of execution in Python methods [duplicate]

This question already has answers here:
Assigning to variable from parent function: "Local variable referenced before assignment" [duplicate]
(5 answers)
Closed 9 years ago.
I've tried looking at a few different examples, but I'm not really sure why this isn't working. Say I've some code like this:
def loadVariable():
global count
count = 0
def loadDictionary():
location = 'some location'
global myDict
myDict = pickle.load(open(location, 'rb'))
def main():
loadVariable()
loadDictionary()
for item in myDict:
if item.startswith("rt"):
count += 1
item = item[3:]
if __name__ == '__main__':
main()
To my eyes, the if statement is executed which starts the main() method. Then, the variable which is global is loaded, the dictionary is loaded and the for loop is executed.
However, when I run the code I am told that the local variable count is referenced before its assignment. Why is that happening?
Edit (Explaining some of the things I've written in comments):
This doesn't work (although I think that's because global is used wrong here):
global count
def loadVariables()
count = 0
def main():
loadVariables()
rest of code etc
This doesn't work either:
def loadVariables()
count = 0
def main():
global count
loadVariables()
rest of code etc
The only way thus far I've gotten it to work is using the link provided above, which is to treat the count as a list, like so:
def loadVariables():
global count
count = [0]
def main():
loadVariables():
rest of code etc
count[0] += 1
global means that within the function containing the global declaration, the name in the global declaration refers to a global variable. It does not mean "this thing is a global variable; treat it as global everywhere." In main, the names count and myDict refer to local variables, because main does not declare that it wants to use the globals.
The issue is that you're not declaring count as a global variable in the main function, so when the compiler sees that you're (eventually) assigning to it, it assumes that it's a local variable. Since it's value is read before it's assigned, you get an exception.
So, the most basic fix is just to add global count at the top of main(), but I think avoiding globals would be a better option. Why not have loadVariable and loadDictionary return their results, rather than assigning them to globals? If in main() you did count = loadVariable(), count would be a local variable, and you'd have no problems later trying to reassign it.
Here's a simple example of how global works
global_var = 0
def updater():
global global_var
global_var += 1
def stuff(x):
updater()
return global_var + x
if __name__ == '__main__':
stuff(2) # returns 3

how to get the pointer to the current function in python? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Python code to get current function into a variable?
is there a convenient way to get to pointer of current function?
for example:
current_func_ref = None
def func():
current_func_ref = ___ #something need to fill
do something..
Ok this is a bit cheeky, not very generic like you might want, but here it is anyway:
current_func_ref = None
def func():
global current_func_ref
current_func_ref = func

Categories

Resources