vesii
vesii

Reputation: 3128

Solving error: local variable 'counter' referenced before assignment

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.

Upvotes: 2

Views: 400

Answers (3)

Leonardo Scotti
Leonardo Scotti

Reputation: 1080

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

Upvotes: 1

Granth
Granth

Reputation: 384

You should move global counter inside the functions.

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

Upvotes: 0

Safwan Samsudeen
Safwan Samsudeen

Reputation: 1707

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

Upvotes: 3

Related Questions