问题
I want to define a few variables in my main python script and use them in a function which is defined in a separate module. Here is an example code. Lets say the main script is named main.py and the module is called mod.py.
Mod.py
def fun():
print a
main.py
from mod import *
global a
a=3
fun()
Now, this code gives me an error
NameError: global name 'a' is not defined
Can anyone please explain why the error is generated (i mean, a variable defined as global should be available to all functions, right?) and what may be a work-around? I already know about these two options and don't want to take any of these
- Define the variable in the module instead of the main script.
- pass the variable as argument to the function.
If there is any other option, please suggest.
Edit
I dont want to take the above options because
- currently these values are fixed for me. But I suspect they may change in future (for example, database name and host ip). So, I want to store them as variables in one place. So that it becomes easy to edit the script in future. If I define the variables in each module, I will have to edit all of them.
- I don't want to pass them in the functions because there are too many of them, some 50 or so. I know I can pass them as **kwarg, but that doesn't look too nice.
回答1:
Global variables shared among modules are generally a bad idea. If you need them though (for example for some configuration purposes), you can do it like this:
global_config.py
# define the variable
a = 3
main.py
import global_config
def fun():
# use the variable
print(global_config.a)
回答2:
This:
a variable defined as global should be available to all functions, right?
is just not true. That's not how global variables work; they are available to all functions in the module where they are defined.
You don't explain what you're doing or why those solutions don't work for you, but generally speaking global variables are a bad idea; passing the value explicitly is almost always the way to go.
来源:https://stackoverflow.com/questions/30074273/global-variable-defined-in-main-script-cant-be-accessed-by-a-function-defined-i