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!
Global variables can be used by everyone, both inside of functions and outside.
The variables that are defined inside the methods can be accessed within that method only by simply using the variable name. Example – var_name. If you want to use that variable outside the method or class, you have to declared that variable as a global.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With