I wanted to define a global variable in main, i.e., a variable that can be used by any function I call from the main function.
Is that possible? What'd be a good way to do this?
Thanks!
I wanted to define a global variable in main, i.e., a variable that can be used by any function I call from the main function.
Is that possible? What'd be a good way to do this?
Thanks!
What you want is not possible*. You can just create a variable in the global namespace:
myglobal = "UGHWTF"
def main():
global myglobal # prevents creation of a local variable called myglobal
myglobal = "yu0 = fail it"
anotherfunc()
def anotherfunc():
print myglobal
DON'T DO THIS.
The whole point of a function is that it takes parameters. Just add parameters to your functions. If you find that you need to modify a lot of functions, this is an indication that you should collect them up into a class.
*
To elaborate on why this isn't possible: variables in python are not declared - they are created when an assignment statement is executed. This means that the following code (derived from code posted by astronautlevel) will break:
def setcake(taste):
global cake
cake = taste
def caketaste():
print cake #Output is whatever taste was
caketaste()
Traceback (most recent call last):
File "prog.py", line 7, in <module>
caketaste()
File "prog.py", line 5, in caketaste
print cake #Output is whatever taste was
NameError: global name 'cake' is not defined
This happens because when caketaste
is called, no assignment to cake
has occurred. It will only occur after setcake
has been called.
You can see the error here: http://ideone.com/HBRN4y
A variable created inside a method (e.g., main) is local by definition. However, you can create a global variable outside the method, and access and change its value from side any other method.
To change its value use the global
keyword.
You need to use global
statements. These are relatively simple. To do this, simply define a variable as global before defining the variable itself.
For example:
def setcake(taste):
global cake
cake = taste
def caketaste():
print cake
setcake('tasty')
caketaste() #Output is tasty
EDIT: Sorry, it seems that I misread your question. Allow me to try answering it properly now.
def printcake():
print cake #This function prints the taste of cake when called
def setcake(taste, printq):
global cake #This makes sure that cake can be called in any function
cake = taste #sets cake's taste
if printq: #determines whether to print the taste
printcake()
setcake('good', True) #Calls the function to set cake. Tells it to print result. The output is good
The output, as seen in code: http://ideone.com/dkAlEp