Solving error: local variable 'counter' referenced before assignment

Viewed 174

Small question about globals. I have the following code:

counter = 0
class A():
    global counter

    def connect():
        counter += 1
        print("Opening connection",counter)
        # DO STUFF

    def disconnect():
        counter -= 1
        print("Closing connection",counter)
        # DO STUFF

Each time I connect or disconnect, I want to know the number of opened connections counter (not just for one instance, rather for all of the instances, so it should be static). But when running the code I get:

local variable 'counter' referenced before assignment

Why is that? Consider that A() is located in other file than main.

3 Answers

As said in the comments, global declaration only works in a function or a method.

counter = 0
class A():
    def connect():
        global counter
        counter += 1
        print("Opening connection",counter)
        # DO STUFF

    def disconnect():
        global counter
        counter -= 1
        print("Closing connection",counter)
        # DO STUFF

You have to do this:

counter = 0
class A():

    def connect():
        global counter
        counter += 1
        print("Opening connection",counter)
        # DO STUFF

    def disconnect():
        global counter
        counter -= 1
        print("Closing connection",counter)
        # DO STUFF

You should move global counter inside the functions.

Also if you are using multithreading/multiprocessing you should use a semaphore while updating the counter.

Related