Search code examples
pythonmoduleglobal-variables

Access to global variables from a module in Python?


let's start with a basic code that uses a global variable :

def fun():
    print(gvar)
gvar = 3

fun()

that of course prints "3" in the console.

Then, I move my function "fun" in a module "mymod", and do :

from mymod import *
gvar=3
fun()

The result is a NameError exception (gvar is not found)

How can I solve this ? I have to mention that I need to access to various global variables which name is not always the same (the context is complex and I do not describe it now to focus on the problem I have for now)


Solution

  • The only global variables python has, are module scoped. So in your case the variable gvar is not visible in the module mymod.

    If you want to use gvar in an imported module, pass gvar as parameter to a function of mymod. If gvar belongs to mymod, define it there.