user937284
user937284

Reputation: 2634

Python singleton again / how to use class attributes?

I would like to have a singleton class in Python with Java like "static class attributes". I read the several posts existing on Python singletons and can not find a solution except using a simple module as singleton.

Is there a way to extends this code (PEP318) to use it with "static class attributes" that I can access from the functions?

def singleton(cls):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance

@singleton
class MyClass:
    ...

Upvotes: 0

Views: 4854

Answers (1)

Aya
Aya

Reputation: 41950

TBH, I've always found the singleton to be an anti-pattern.

If you want an object which will only ever have a single instance, then why bother even instantiating anything? Just do something like...

class MyCounter(object):
    count = 0

    @classmethod
    def inc(cls, delta=1):
        cls.count += delta

>>> MyCounter.count
0
>>> MyCounter.inc()
>>> MyCounter.count
1
>>> MyCounter.inc(5)
>>> MyCounter.count
6

Upvotes: 7

Related Questions