A global variable defined in the main script cannot be accessed by a function defined in another module

I want to define multiple variables in my main python script and use them in a function that is defined in a separate module. Here's some sample code. Let's say the main script is called 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 is giving me error

NameError: global name 'a' is not defined

      

Can someone explain the reason for the error (I mean that a variable defined as global should be available to all functions, right?) And what could be a workaround? I already know about these two options and do not want to accept any of these

  • Define a variable in the module instead of the main script.
  • pass the variable as an argument to the function.

If there is another option, please suggest.

Edit

I don't want to use the above options because

  • These values ​​are currently fixed for me. But I suspect they may change in the future (e.g. database name and host IP). Therefore, I want to store them as variables in one place. So it becomes easier to edit the script in the future. If I define variables in each module, I have to edit all of them.
  • I don't want to pass them to functions because there are too many of them, about 50 or so. I know I can pass them as ** kwarg, but it doesn't look good.
+1


source to share


2 answers


Shared globals between modules are generally a bad idea. If you need them (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


source


It:

a variable defined as global should be available to all functions, right?



just wrong. This is 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 these solutions don't work for you, but generally speaking, globals are a bad idea; passing a value explicitly is almost always the way to go.

+1


source







All Articles