2

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
  • 1
    "global" declaration only works in a function/method. Commented Nov 22, 2020 at 10:01
  • you don't need to write lobal counter in the class but you have to do it in the methods Commented Nov 22, 2020 at 10:03
  • @Michael Butscher, I know, in fact i edited, I made a mistake while writing Commented Nov 22, 2020 at 10:08

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. If I have two instances of A(), they share the counter right?
Yup. P.S - This comment word limit is irritating.
1

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

Comments

0

You should move global counter inside the functions.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.