Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
singleton using metaclass
#1
i need to write a singleton so i looked up some examples. here's one of them from https://stackoverflow.com/questions/6760...on#6798042
class _Singleton(type):
    """ A metaclass that creates a Singleton base class when called. """
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class Singleton(_Singleton('SingletonMeta', (object,), {})): pass

class Logger(Singleton):
    pass
i've just read about metaclasses but i don't understand how the above example uses a metaclass. shouldn't it be? -->
class _Singleton(type):
    """ A metaclass that creates a Singleton base class when called. """
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class Singleton(metaclass=_Singleton('SingletonMeta', (object,), {})): pass # notice the metaclass

class Logger(Singleton):
    pass
however i still want isinstance(inst, Singleton) to be True.
Reply


Messages In This Thread
singleton using metaclass - by bb8 - Feb-10-2018, 03:27 PM
RE: singleton using metaclass - by Gribouillis - Feb-10-2018, 10:54 PM
RE: singleton using metaclass - by bb8 - Feb-11-2018, 05:19 AM
RE: singleton using metaclass - by Gribouillis - Feb-11-2018, 08:32 AM
RE: singleton using metaclass - by bb8 - Feb-11-2018, 06:34 PM
RE: singleton using metaclass - by Gribouillis - Feb-11-2018, 06:45 PM
RE: singleton using metaclass - by bb8 - Feb-12-2018, 04:43 PM
RE: singleton using metaclass - by Gribouillis - Feb-12-2018, 05:00 PM
RE: singleton using metaclass - by bb8 - Feb-12-2018, 05:31 PM
RE: singleton using metaclass - by Gribouillis - Feb-12-2018, 05:47 PM
RE: singleton using metaclass - by bb8 - Feb-12-2018, 06:17 PM
RE: singleton using metaclass - by Gribouillis - Feb-12-2018, 06:25 PM
RE: singleton using metaclass - by bb8 - Feb-13-2018, 01:27 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Prefs class: singleton or something else? PatM 7 1,262 Dec-12-2022, 11:01 PM
Last Post: PatM
  initialisation and metaclass GuiOhm 1 1,842 Mar-09-2020, 03:30 PM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

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