Global variables in Python to share variable across files

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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?

Answers

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.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/29304931/global-variables-in-python-to-share-variable-across-files

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils