5

Consider the following code:

def apples():
    print(apples.applecount)
    apples.applecount += 1

apples.applecount = 0
apples()
>>> 0
apples()
>>> 1
# etc

Is this a good idea, bad idea or should I just destroy myself? If you're wondering why I would want this, I got a function repeating itself every 4 seconds, using win32com.client.Dispatch() it uses the windows COM to connect to an application. I think it's unnecessary to recreate that link every 4 seconds. I could of course use a global variable, but I was wondering if this would be a valid method as well.

2 Answers 2

5

It would be more idiomatic to use an instance variable of a class to keep the count:

class Apples:
    def __init__(self):
        self._applecount = 0

    def apples(self):
        print(self._applecount)
        self._applecount += 1

a = Apples()
a.apples()  # prints 0
a.apples()  # prints 1

If you need to reference just the function itself, without the a reference, you can do this:

a = Apples()
apples = a.apples

apples()  # prints 0
apples()  # prints 1
Sign up to request clarification or add additional context in comments.

1 Comment

Great suggestion. Basically, when you want to put state (in the form of explicit variables) and functionality together, what you want is usually a class.
4

It is basically a namespaced global. Your function apples() is a global object, and attributes on that object are no less global.

It is only marginally better than a regular global variable; namespaces in general are a good idea, after all.

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.