Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Global Variables - Not Defined?

I'm running into an issue where a global variable isn't "remembered" after it's modified in 2 different functions. The variable df is supposed to be a data frame, and it doesn't point to anything until the user loads in the right file. This is similar to something I have (using pandas and tkinter):

global df

class World:

    def __init__(self, master):
        df = None
        ....

    def load(self):
        ....
        df = pd.read_csv(filepath)

    def save(self):
        ....
        df = df.append(...)

save() is always called after load(). Thing is, when I call save(), I get the error that "df is not defined." I thought df got its initial assignment in init(), and then got "updated" in load()? What am I doing wrong here?

like image 541
Axioms Avatar asked Apr 08 '18 08:04

Axioms


People also ask

Why is my global variable undefined?

The reason the first alert is undefined is because you re-declared global as a local variable below it in the function. And in javascript that means from the top of the function it is considered the local variable. The one below it works because just above the alert you gave it a value.

Why is Python saying my variable is not defined?

The Python "NameError: name is not defined" occurs when we try to access a variable or function that is not defined or before it is defined. To solve the error, make sure you haven't misspelled the variable's name and access it after it has been declared.

How are global variables defined in Python?

A global variable in Python is often declared as the top of the program. In other words, variables that are declared outside of a function are known as global variables. You can access global variables in Python both inside and outside the function.

How do you define a global variable?

In computer programming, a global variable is a variable with global scope, meaning that it is visible (hence accessible) throughout the program, unless shadowed. The set of all global variables is known as the global environment or global state.


1 Answers

You have to use global df inside the function that needs to modify the global variable. Otherwise (if writing to it), you are creating a local scoped variable of the same name inside the function and your changes won't be reflected in the global one.

p = "bla"

def func():
    print("print from func:", p)      # works, readonly access, prints global one

def func1():
    try: 
        print("print from func:", p)  # error, python does not know you mean the global one
        p = 22                        # because function overrides global with local name   
    except UnboundLocalError as unb:
        print(unb)
        
def func2():
    global p
    p = "blubb"                       # modifies the global p

print(p)
func()
func1()
print(p)
func2()
print(p)

Output:

bla   # global

print from func: bla    # readonly global

local variable 'p' referenced before assignment  # same named local var confusion

bla    # global
blubb  # changed global
like image 153
Patrick Artner Avatar answered Sep 30 '22 13:09

Patrick Artner