What is the best way of implementing singleton in Python

Use a Metaclass I would recommend Method #2, but you’re better off using a metaclass than a base class. Here is a sample implementation: class Singleton(type): _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 Logger(object): __metaclass__ = Singleton Or in Python3 class Logger(metaclass=Singleton): … Read more

__metaclass__ in Python 3

Python 3 changed how you specify a metaclass, __metaclass__ is no longer checked. Use metaclass=… in the class signature: class Table(object, metaclass=MetaTable): Demo: >>> class MetaTable(type): … def __getattr__(cls, key): … temp = key.split(“__”) … name = temp[0] … alias = None … if len(temp) > 1: … alias = temp[1] … return cls(name, alias) … Read more

“MetaClass”, “__new__”, “cls” and “super” – what is the mechanism exactly?

OK, you’ve thrown quite a few concepts into the mix here! I’m going to pull out a few of the specific questions you have. In general, understanding super, the MRO and metclasses is made much more complicated because there have been lots of changes in this tricky area over the last few versions of Python. … Read more

Automatically setting an enum member’s value to its name

Update: 2017-03-01 In Python 3.6 (and Aenum 2.01) Flag and IntFlag classes have been added; part of that was a new auto() helper that makes this trivially easy: >>> class AutoName(Enum): … def _generate_next_value_(name, start, count, last_values): … return name … >>> class Ordinal(AutoName): … NORTH = auto() … SOUTH = auto() … EAST = … Read more

Metaclass Mixin or Chaining?

A type can have only one metaclass, because a metaclass simply states what the class statement does – having more than one would make no sense. For the same reason “chaining” makes no sense: the first metaclass creates the type, so what is the 2nd supposed to do? You will have to merge the two … Read more

Customary To Inherit Metaclasses From type?

There are subtle differences, mostly relating to inheritance. When using a function as a metaclass, the resulting class is really an instance of type, and can be inherited from without restriction; however, the metaclass function will never be called for such subclasses. When using a subclass of type as a metaclass, the resulting class will … Read more