Py Meta Utils

Included Metaclass Utilities

Singleton

Singleton is an included metaclass that makes any class utilizing it a singleton:

from py_meta_utils import Singleton


class YourSingleton(metaclass=Singleton):
    pass


instance = YourSingleton()
assert instance == YourSingleton()

Classes using Singleton can be subclassed, however, you must inform the base class of your subclass:

from py_meta_utils import Singleton

class BaseSingleton(metaclass=Singleton):
    pass

class Extended(BaseSingleton):
    pass

BaseSingleton.set_singleton_class(Extended)
base_instance = BaseSingleton()
extended_instance = Extended()
assert base_instance == extended_instance == BaseSingleton() == Extended()

deep_getattr

deep_getattr(clsdict, bases, 'attr_name', [default])

deep_getattr acts just like getattr would on a constructed class object, except this operates on the pre-class-construction class dictionary and base classes. In other words, first we look for the attribute in the class dictionary, and then we search all the base classes (in method resolution order), finally returning the default value if the attribute was not found in any of the class dictionary or base classes (or it raises AttributeError if default not given).

OptionalMetaclass and OptionalClass

try:
    from optional_dependency import SomeClass
except ImportError:
    from py_meta_utils import OptionalClass as SomeClass


class Optional(SomeClass):
    pass

License

MIT