33. metaclass
— Metaclasses¶
This module defines some metaclasses for constructing application classes with specialized behavior. Currently we have metaclasses to construct singleton classes and classes with an instance registry.
33.1. Classes defined in module metaclass¶
- class metaclass.SingletonMeta[source]¶
Metaclass for creating singleton classes
Singleton classes have only a single instance. Every creation of a new instance just returns the same instance.
Examples
>>> class SingletonClass(metaclass=SingletonMeta): pass >>> a = SingletonClass() >>> b = SingletonClass() >>> print(a is b) True
- class metaclass.RegistryMeta(name, bases, namespace, raise_exist=True)[source]¶
Metaclass for creating registry classes.
Registry classes register their instances in a dict. The first argument of the __init__ function must be the key to use for registering the instance. By default the class will raise an exception when trying to create an instance with an already registered key. This can be silenced by passing a parameter
raise_exist=False
to the metaclass (see examples). Registered instances are persistent: they have to be explicitely deleted from the registry dict.Examples
>>> class RegistryClass(metaclass=RegistryMeta): ... def __init__(self, key): ... pass >>> a = RegistryClass('a') >>> b = RegistryClass('a') Traceback (most recent call last): ... ValueError: RegistryClass('a') already exists >>> b = RegistryClass('b') >>> print(a is b) False >>> class SilentRegistryClass(metaclass=RegistryMeta, raise_exist=False): ... def __init__(self, key): ... pass >>> a = SilentRegistryClass('a') >>> b = SilentRegistryClass('a') >>> a is b True
- property dict¶
Return the cls registry as a dict