j4ck j4ck - 1 year ago 61
Python Question

Accessing a variable from outer scope via global keyword in Python

As per this Question's accepted answer, I understand I cannot create pure global variables. Okay, cool.

However, he then goes on and says:

[..]all you can do is make a variable in a particular scope. (If you make a variable inside the Python interpreter, and then import other modules, your variable is in the outermost scope and thus global within your Python session.[..]

Okay, so we can't assign globals in the original sense, but it appears to be possible to access variables in the outermost scope from within a package, via the
keyword, correct?

I am then, apparently, missing something crucial in my efforts to access a variable passed to my python program via commandline arguments.

My program has the usual
, which handles argument parsing and executes code from my python module

has code that relies on input via command line arguments. However, I seem to fail at making these arguments available to

My package's layout is:

- __main__.py
- backend/


import argparse

# Setup ArgParser
parser = argparse.ArgumentParser(description="Fancy Description of program.")
parser.add_argument('--tar', nargs=1, dest='target',
help='Specify output folder.',

target_dir = args.target[0]

# Import backend now that our variable is set.
from backend.direction import direction

And my

global target_dir

Running this raises a
NameError: 'target_dir' is not defined
So where's the poop ?
Am I assuming an impossibility here, or am I simply messing up on declaration?


I am not clear what your problem actually is. Is it not possible to do the following?

import backend

if __name__ == "__main__":
    # parse arguments

As Daniel Roseman suggested, if there are many backend functions requiring access to these variables then you should consider using a class, and class properties, to store the variables.

class argreceive():
    def __init__(self,args):
        self.args = args