简体   繁体   中英

Why doesn't this simple Python script run?

I am writing a large program where I need to pass data/variables between functions. Note: I'm a hobbyist and OOP is out of my grasp, so just looking for a non-OOP answer!

I'm using functions to try and make the script modular and avoid having one long messy script. But the program uses a dataframe and lots of different variables which many of the functions will need to access. I don't want to specify every single variable in every function call so would like to be able to access global variables from individual functions. I can do this when the def function(): is in the same script, but I am running into a problem when I try and call global variables when importing a function from a script. Simple reprex:

from test_func import p_func

a = "yes!"

p_func()

calling p_func() from test_func.py

def p_func():
    global a
    print(a)

generates the error:

Traceback (most recent call last):
  File "test.py", line 5, in <module>
    p_func()
  File "test_func.py", line 5, in p_func
    print(a)
NameError: name 'a' is not defined

What am I missing?

You need to change your import line to be:

from test_func import p_func, a

Variables are imported from other modules the same way that functions are.

That said. This is really, really a bad idea as others above has said. Your best off putting all your variables into a single data structure of some sort

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM