0

I'd like to assign an "external" value for a global variable in a standalone Python program from a command line parameter and let my functions manipulate it (please disregard the fact that using global variables is discouraged in general). I have tried like the following:

def my_function():
    global global_var
    global_var+=1

def main(argv): 

    global_var = sys.argv[1]
    my_function()

if __name__ == "__main__":
    main(sys.argv)

But it doesn't work because of the following reason:

NameError: global name 'global_var' is not defined

The problem occurs in the global global_var line in my_function, the function seemingly cannot recognize this as global despite the explicit qualification as like this. I guess that this is because my global_var doesn't exist before my_function()'s definition. But I cannot define my global_var at the beginning of the code (before my_function()) either because main() should stand at the end and main() parses the program parameters. Right?

Fruchtzwerg
  • 10,999
  • 12
  • 40
  • 49
Hendrik
  • 1,158
  • 4
  • 15
  • 30
  • 1
    "because main() should stand at the end and main() parses the program parameters." No, Python is not C nor Java. `main` is an ordinary function that just happen to be called `main`. – DeepSpace Feb 22 '17 at 09:12
  • OK, thank, didn't know that. I have changed the order of the two functions (`main()` first, `my_function()` second), but still the same error exists. – Hendrik Feb 22 '17 at 09:24

0 Answers0