Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

global variable inside main function python

Tags:

python

scope

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!

like image 706
Dnaiel Avatar asked May 11 '13 22:05

Dnaiel


People also ask

Can you use global variables in functions Python?

Global variables can be used by everyone, both inside of functions and outside.

How do you access a variable inside a function in Python?

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.

Are variables inside main 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.


1 Answers

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

like image 185
Marcin Avatar answered Sep 23 '22 04:09

Marcin