0

I have a Python 3.6.4 program on windows which uses a configuration file, config.py, to define global variables, as well as the main.py script which does other stuff. My config.py contains a string named "variable" with "value" as its value:

# config.py
global variable
variable = "value"

If I import all variables in main.py and try to print(variable), it works fine. But if I try: variable AFTERWARDS, then it fails on the first print(variable). Sorry for the long code, I tried to reproduce the issue with smaller pieces of code and it worked fine, which really confuses me:

# main.py
import argparse, logging, sys
from config import *

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-v',
                    '--verbose',
                    action='store_true',
                    help="Rapporter davantage d'information.")
    parser.add_argument('-l',
                    '--journal',
                    action='store',
                    default=None,
                    help="Spécifier le nom du journal.")
    parser.add_argument('--csv',
                    action="store_true",
                    help="Exporter les résultats vers un fichier de sortie CSV.")
    args = parser.parse_args()

    # Configuration du journal
    log_frmt = "%(asctime)s[%(levelname)s] %(message)s"
    date_frmt = "%Y-%m-%d %H:%M:%S "
    if args.verbose:
        log_lvl = logging.DEBUG
    else:
        log_lvl = logging.INFO

    logging.basicConfig(filename=args.journal,
                    format=log_frmt,
                    datefmt=date_frmt,
                    level=log_lvl)

    logging.info(f"Journal initié : {args.journal}")

    if args.csv:
        print(variable)
        sys.exit()

        #try:
            #print(variable)
            #variable
            #logging.debug(f"variable = {variable}")
            #sys.exit()
        #except NameError:
            #variable = None
            #logging.warning("variable non-défini, initialisé à None")
            #sys.exit()

if __name__ == '__main__':
    main()

The output is:

$ python main.py --csv
2018-03-14 16:44:20 [INFO] Journal initié : None
value

...which is what you'd expect. But if I uncomment the last part, AFTER sys.exit():

    ...
    logging.info(f"Journal initié : {args.journal}")

    if args.csv:
        print(variable)
        sys.exit()

        try:
            print(variable)
            variable
            logging.debug(f"variable = {variable}")
            sys.exit()
        except NameError:
            variable = None
            logging.warning("variable non-défini, initialisé à None")
            sys.exit()

if __name__ == '__main__':
main()

...it fails on the first print(variable):

$ python main.py --csv
2018-03-14 16:55:58 [INFO] Journal initié : None
Traceback (most recent call last):
  File "main.py", line 52, in <module>
    main()
  File "main.py", line 38, in main
    print(variable)
UnboundLocalError: local variable 'variable' referenced before assignment

What could possibly be causing this? Nothing else changed, I saved my script, reloaded python (I run it from git bash, not from the python console which doesn't reload modules)... what else can I try?

I tried reproducing this with a simpler script, with no logging and no argparse, but could reproduce it.

Thank you.

  • Notice that this is not a `NameError` but an UnboundLocalError. When you assign to a variable somewhere later in the same scope, python recognizes this (even before you come to the command!) and thinks the variable is local. You have to explicitly say that the variable is global via `global variable`. Also the `global` in your `config.py` is superflous, the variable is already global. – syntonym Mar 14 '18 at 21:09
  • Thank you, I somehow missed the different error code, and the duplicate you identified and your comment helped me resolve the issue. – user2432959 Mar 14 '18 at 23:30

0 Answers0