Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Decorating a class-help
#1
Hi!

I'm not too sure why the following code is working:

class Statics():
    lock = threading.Lock()


def thread_safe(func):
    def inner(*args,**kwargs):
        with Statics.lock:
            result = func(*args, **kwargs)
        return result
    return inner


@thread_safe
def singleton(class_):
    instances = {}
    def getinstance(*args, **kwargs):
        if class_ not in instances:
            instances[class_] = class_(*args, **kwargs)
        return instances[class_]
    return getinstance
Specifically,the singleton decorator,which decorates a class,is working, but I don't understand why.
Usually a class decorator returns another class.
Reply
#2
A python class is not only a class, it is also a callable that returns instances. With this decorator, after
@singleton
class A:
    pass
the object named A in the current namespace is not a class. Instead it is a function that returns A instances. The code supposes that you're not interested in anything else about A. You can still write
a = A()
and get (the only) instance of the class. But you cannot do A.some_static_member and get the corresponding member of class A.

IMHO it is a huge waste of time to spend hours on the singleton pattern in python. Python is for responsible adults, so if you want a singleton, just create a single instance.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020