0

I have python function that needs to set a global variable on it's first run and modify it on other runs I've tried implementing this as follows:

def foo():
    if 'some_var' in globals():
        some_var = some_var + 1
    else:
        global some_var
        some_var = 0

However, I get a syntax error:

SyntaxError: name 'some_var' is used prior to global declaration

Why is this? How do I implement this functionality correctly?

Yakov Dan
  • 2,157
  • 15
  • 29

2 Answers2

1

moving global some_var to the top of the function should be fine:

def foo():
    global some_var
    if 'some_var' in globals():
        some_var = some_var + 1
    else:
        some_var = 0
Yeganeh Salami
  • 575
  • 7
  • 29
0

Please see name 'times' is used prior to global declaration - But IT IS declared!

The correct code would be:

def foo():
    if 'some_var' not in globals():
        global some_var 
        some_var=0
    else:
        some_var+=1
Marcel Wilson
  • 3,842
  • 1
  • 26
  • 55
Mikhail Genkin
  • 3,247
  • 4
  • 27
  • 47