简体   繁体   中英

Accessing variable in module / Module scope in Python

I would like to use a variable that I define in my application inside of a module.

The folder structure:

myapp.py

modules/checkargs.py

modules/ init .py (an empty file)

Main app (myapp.py):

_PARAMETERS = {
    'stuff': 'here'
}

from modules.checkargs import checkargs

if __name__ == "__main__":
    checkargs(sys.argv[1:])

checkargs.py:

def checkargs(argv):

    global _PARAMETERS;

    #more Python insanity here

The error:

NameError: global name '_PARAMETERS' is not defined

In general, you should avoid this style of programming. Modules shouldn't rely on global variables defined in other modules. A better solution would be to pass _PARAMETERS in to checkargs , or move _PARAMETERS to a file that can be shared by multiple modules.

Passing the data to checkargs

Generally speaking, relying on global variables is a bad idea. Perhaps the best solution is to pass PARAMETERS directly into your checkargs function.

# checkargs.py
def checkargs(argv, parameters):
    ...

# myapp.py
if __name__ == "__main__":
    checkargs(sys.argv[1:], _PARAMETERS)

Creating a shared data module

If you have data that you want to share between modules, you can place that data in a third module that every other module imports:

# modules/shared.py
PARAMETERS = {...}

# myapp.py
from modules.shared import PARAMETERS

# checkargs.py
from modules.shared import PARAMETERS

Other solutions

There are other solutions, though I think the above two solutions are best. For example, your main program can copy the parameters to the checkargs module like this:

# myapp.py
import checkargs
checkargs._PARAMETERS = _PARAMETERS
...

You could also have checkargs directly reference the value in your main module, but that requires a circular import. Circular imports should be avoided.

Why would it be defined? It's from a different module. Inside checkargs.py, you'd need to do:

from myapp import _PARAMETERS

However:

  1. You shouldn't name it with a _ then, since that implies private/protected variables.
  2. You should probably pass the dictionary from myapp into the checkargs functions instead of importing it there. If you don't, you're creating a circular import, which is logically terrible and doesn't actually work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM