-1

I have the following code:

counter = 0
def function_1():
  func_2(counter)

def func_2(counter):
  func_3(counter)

def func_3(counter):
   counter += 1

My goal is to keep track of counter incrementation in func_3() in all other functions.

I tried to make counter global

counter = 0
def function_1():
  global counter
  func_2(counter)

def func_2(counter):
  func_3(counter)

def func_3(counter):
   counter += 1

but it does not work, the counter incrementation is just local to func_3()

Any hints?

user123892
  • 1,243
  • 3
  • 21
  • 38
  • 2
    Why do you pass counter as an argument if it's available from the global scope? Int integer are copied, not referenced – politinsa Oct 11 '19 at 14:08
  • 2
    Possible duplicate of [Using global variables in a function](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function) –  Oct 11 '19 at 14:12
  • 2
    Counter is local in func_3 because you are passing it as a argument, which is local to the function. If you would like to have it global, you need to put global to func_3 (as you have it in function_1) and remove argument (that counter in ()). And King's jester comment is useful, there is a lot of information in that thread. – Dolfa Oct 11 '19 at 14:15
  • Thank you @politinsa, I realise now how silly I've been :-) – user123892 Oct 11 '19 at 14:22

2 Answers2

3

I tried to find an easy to understand explanation for you, but they all seemed to complicated.

The reason that you are seeing counter as a local variable inside your functions is because you are defining it in the function definition: def func_2(counter):.

To use the global counter inside a function you need to do it like this:

counter = 0

def function_1():
  func_2()

def func_2():
  func_3()

def func_3():
   global counter
   counter += 1

Cargo23
  • 3,064
  • 16
  • 25
  • 1
    Thank you, @politinsa comment made me realise my error, if counter is of global scope, why did I pass it as an argument? :-) – user123892 Oct 11 '19 at 14:20
1

You can use globals().update(locals()), example:

counter = 0
def function_1():
  func_2()

def func_2():
  func_3()

def func_3():
  counter += 1
  globals().update(locals())

or use global method

counter = 0
def function_1():
  func_2()

def func_2():
  func_3()

def func_3():
  global counter
  counter += 1