Search code examples
pythonglobal-variables

how can I change the global variable in each function without the functions affecting each other in Python?


My global variable count=0 is being changed in the function (method) below:

def Counter(counter,boolean=False)->int:
    if boolean:
        counter+=1
    else:
        counter=0

    return counter

and other functions uses Counter function:

def func1():
    global count
    count=Counter(count,True)
    print("func1:",count)

def func2():
    global count
    count=Counter(count,True)
    print("func2:",count)

When run these functions one more time like for loop

for _ in range(3):
    func1()
    func2()

the output is:

func1:1
func2:2
func1:3
func2:4
func1:5
func2:6

But output must be like this:

func1:1
func2:1
func1:2
func2:2
func1:3
func2:3

I researched different ways but could not find an answer. How can I do that?


Solution

  • Why previous code didn't work?

    The global keyword makes the counter variable accessible from both functions.
    Using global variable is a bad-practice, don't do that.

    How to achieve what you asked?

    The following word assigns a counter for each of the functions, which modify it on each call.

    
    def func1():
        func1.count+=1
        print("func1:", func1.count)
    
    def func2():
        func2.count += 1
        print("func1:", func2.count)
    
    func1.count=0
    func2.count=0
    
    for _ in range(3):
        func1()
        func2()
    

    More about

    What you ask, is how to use static-variable in a python function.
    The term 'function static variable' refers to a variable that is accessible and owned by a function.
    Python doesn't support static variables in a straight-forward manner such as in languages such as C# or Java, but there are other beautiful solutions in this thread, those are more complex and require the usage of decorators - so I didn't mention them.