pyTooling.MetaClasses

The MetaClasses package implements Python meta-classes (classes to construct other classes in Python).

Hint

See high-level help for explanations and usage examples.

Variables

Functions

Exceptions

Classes

  • ExtendedType: An updates meta-class to construct new classes with an extended feature set.

  • SlottedObject: Classes derived from this class will store all members in __slots__.


Variables

pyTooling.MetaClasses.M

A type variable for methods.

~M

Functions

pyTooling.MetaClasses.slotted(cls)[source]
pyTooling.MetaClasses.mixin(cls)[source]
pyTooling.MetaClasses.singleton(cls)[source]
pyTooling.MetaClasses.abstractmethod(method)[source]

Mark a method as abstract and replace the implementation with a new method raising a NotImplementedError.

The original method is stored in <method>.__wrapped__ and it’s doc-string is copied to the replacing method. In additional field <method>.__abstract__ is added.

Warning

This decorator should be used in combination with meta-class ExtendedType. Otherwise, an abstract class itself doesn’t throw a AbstractClassError at instantiation.

example.py

class Data(mataclass=ExtendedType):
  @abstractmethod
  def method(self) -> bool:
    '''This method needs to be implemented'''
Parameters:

method (TypeVar(M, bound= Callable)) – Method that is marked as abstract.

Return type:

TypeVar(M, bound= Callable)

Returns:

Replacement method, which raises a NotImplementedError.

See also

  • AbstractClassError

  • mustoverride()

  • notimplemented()

pyTooling.MetaClasses.mustoverride(method)[source]

Mark a method as must-override.

The returned function is the original function, but with an additional field <method>.____mustOverride__, so a meta-class can identify a must-override method and raise an error. Such an error is not raised if the method is overridden by an inheriting class.

A must-override methods can offer a partial implementation, which is called via super()....

Warning

This decorator needs to be used in combination with meta-class ExtendedType. Otherwise, an abstract class itself doesn’t throw a MustOverrideClassError at instantiation.

example.py

class Data(mataclass=ExtendedType):
  @mustoverride
  def method(self):
    '''This is a very basic implementation'''
Parameters:

method (TypeVar(M, bound= Callable)) – Method that is marked as must-override.

Return type:

TypeVar(M, bound= Callable)

Returns:

Same method, but with additional <method>.__mustOverride__ field.

See also

  • MustOverrideClassError

  • abstractmethod()

  • notimplemented()


Exceptions

exception pyTooling.MetaClasses.ExtendedTypeError[source]

The exception is raised by the meta-class ExtendedType.

Inheritance

Inheritance diagram of ExtendedTypeError

exception pyTooling.MetaClasses.BaseClassWithoutSlotsError[source]

The exception is raised when a class using __slots__ inherits from at-least one base-class not using __slots__.

Inheritance

Inheritance diagram of BaseClassWithoutSlotsError

exception pyTooling.MetaClasses.BaseClassWithNonEmptySlotsError[source]

Inheritance

Inheritance diagram of BaseClassWithNonEmptySlotsError

exception pyTooling.MetaClasses.BaseClassIsNotAMixinError[source]

Inheritance

Inheritance diagram of BaseClassIsNotAMixinError

exception pyTooling.MetaClasses.DuplicateFieldInSlotsError[source]

Inheritance

Inheritance diagram of DuplicateFieldInSlotsError

exception pyTooling.MetaClasses.AbstractClassError[source]

The exception is raised, when a class contains methods marked with abstractmethod or mustoverride.

See also

@abstractmethod

→ Mark a method as abstract.

@mustoverride

→ Mark a method as must overrride.

MustOverrideClassError

→ Exception raised, if a method is marked as must-override.

Inheritance

Inheritance diagram of AbstractClassError

exception pyTooling.MetaClasses.MustOverrideClassError[source]

The exception is raised, when a class contains methods marked with must-override.

See also

@abstractmethod

→ Mark a method as abstract.

@mustoverride

→ Mark a method as must overrride.

AbstractClassError

→ Exception raised, if a method is marked as abstract.

Inheritance

Inheritance diagram of MustOverrideClassError


Classes

class pyTooling.MetaClasses.ExtendedType(className: str, baseClasses: Tuple[type], members: Dict[str, Any], slots: bool = False, mixin: bool = False, singleton: bool = False)[source]

An updates meta-class to construct new classes with an extended feature set.

Todo

META::ExtendedType Needs documentation.

Todo

META::ExtendedType allow __dict__ and __weakref__ if slotted is enabled

Features:

Inheritance

Inheritance diagram of ExtendedType

Parameters:
Return type:

ExtendedType

static __new__(self, className, baseClasses, members, slots=False, mixin=False, singleton=False)[source]

Construct a new class using this meta-class.

Parameters:
  • className (str) – The name of the class to construct.

  • baseClasses (Tuple[type]) – The tuple of base-classes the class is derived from.

  • members (Dict[str, Any]) – The dictionary of members for the constructed class.

  • slots (bool) – If true, store object attributes in __slots__ instead of __dict__.

  • mixin (bool) – If true, make the class a Mixin-Class. If false, create slots if slots is true. If none, preserve behavior of primary base-class.

  • singleton (bool) – If true, make the class a Singleton.

Return type:

ExtendedType

Returns:

The new class.

Raises:
classmethod _iterateBaseClassPaths(baseClasses)[source]

Return a generator to iterate all possible inheritance paths for a given list of base-classes.

An inheritance path is expressed as a tuple of base-classes from current base-class (left-most item) to object (right-most item).

Parameters:

baseClasses (Tuple[type]) – List (tuple) of base-classes.

Return type:

Generator[Tuple[type, ...], None, None]

Returns:

Generator to iterate all inheritance paths. An inheritance path is a tuple of types (base-classes).

classmethod _checkForAbstractMethods(baseClasses, members)[source]

Check if the current class contains abstract methods and return a tuple of them.

These abstract methods might be inherited from any base-class. If there are inherited abstract methods, check if they are now implemented (overridden) by the current class that’s right now constructed.

Parameters:
  • baseClasses (Tuple[type]) – The tuple of base-classes the class is derived from.

  • members (Dict[str, Any]) – The dictionary of members for the constructed class.

Return type:

Tuple[Dict[str, Callable], Dict[str, Any]]

Returns:

A tuple of abstract method’s names.

classmethod _wrapNewMethodIfSingleton(newClass, singleton)[source]

If a class is a singleton, wrap the _new__ method, so it returns a cached object, if a first object was created.

Only the first object creation initializes the object.

This implementation is threadsafe.

Parameters:
  • newClass – The newly constructed class for further modifications.

  • singleton (bool) – If True, the class allows only a single instance to exist.

Return type:

bool

Returns:

True, if the class is a singleton.

__call__(*args, **kwargs)

Call self as a function.

__delattr__(name, /)

Implement delattr(self, name).

__dir__()

Specialized __dir__ implementation for types.

__getattribute__(name, /)

Return getattr(self, name).

__init__(*args, **kwargs)
__instancecheck__(instance, /)

Check if an object is an instance.

__or__(value, /)

Return self|value.

__prepare__() dict

used to create the namespace for the class statement

__repr__()

Return repr(self).

__ror__(value, /)

Return value|self.

__setattr__(name, value, /)

Implement setattr(self, name, value).

__sizeof__()

Return memory consumption of the type object.

__subclasscheck__(subclass, /)

Check if a class is a subclass.

__subclasses__()

Return a list of immediate subclasses.

__text_signature__ = None
classmethod _wrapNewMethodIfAbstract(newClass)[source]

If the class has abstract methods, replace the _new__ method, so it raises an exception.

Parameters:

newClass – The newly constructed class for further modifications.

Return type:

bool

Returns:

True, if the class is abstract.

Raises:

AbstractClassError – If the class is abstract and can’t be instantiated.

mro()

Return a type’s method resolution order.

class pyTooling.MetaClasses.SlottedObject[source]

Classes derived from this class will store all members in __slots__.

Inheritance

Inheritance diagram of SlottedObject

classmethod GetMethodsWithAttributes(predicate=None)
Parameters:

predicate (Union[TypeVar(TAttr), Iterable[TypeVar(TAttr)], None])

Return type:

Dict[Callable, Tuple[Attribute, ...]]

Returns:

Raises:
class property HasClassAttributes: bool

Check if class has Attributes.

Returns:

True, if the class has Attributes.

class property HasMethodAttributes: bool

Check if class has any method with Attributes.

Returns:

True, if the class has any method with Attributes.