sodiumnitrate
sodiumnitrate

Reputation: 3133

Global variables in Python to share variable across files

I have a Python script that gets a command line argument, and then it is stored as a global variable within the script:

global chain
chain = sys.argv[1]

The script then imports a couple of other files, each containing another function. I am trying to carry the value of this variable to the other functions as well, by doing the following:

def func():
    global chain
    #do stuff

which is contained in another file than the original script.

When I run the script, I get

NameError: global name 'chain' is not defined

What am I missing?

Upvotes: 2

Views: 11510

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599778

global in Python means "within that module". It does not share names across modules.

If you want to access a variable defined in one module from another, simply import it:

from my_module import chain

or, even better, pass it as an argument to func.

Upvotes: 5

Related Questions