API

Package classcore

Foundational class factories and decorators.

Provides ability to create class decorators and metaclasses with customization hooks. The metaclasses can apply class decorators inline during the class construction and initialization process, properly handling cases where decorators replace classes (e.g., dataclasses.dataclass( slots = True )). They also backport the repair mechanism from newer versions of CPython to ensure that the class closure cells are rectified on replaced classes, so that zero-argument super calls function correctly in them.

The classcore.standard subpackage is an example of the decorators and customization hooks being used to provide a set of practical classes and class decorators. Furthermore, the exception classes in the classcore.exceptions module inherit from one of the standard classes, making both the exception classes, themselves, and their instances immutable and concealing their non-public attributes to reduce API noise. I.e., this package “eats its own dog food” and provides practical examples in so doing.

This package is not as magical as it might seem. It does not rely on any exec or eval calls and it does not do anything with ctypes or similar surgical instruments. It relies completely on the documented Python data model and the machinery that it provides. While it is true that metaclasses can be tricky, this package is developed with a deep, highly-evolved understanding of them. We seek simplicity over cleverness and maintain robust tests across multiple Python implementations and versions. The package is also very clean in terms of static type checking (via Pyright).

Module classcore.decorators

Factories which produce metaclass implementations.

classcore.factories.produce_class_constructor(attributes_namer: Callable[[str, str], str], preprocessors: Annotated[Sequence[Annotated[Callable[[type[type], str, list[type], dict[str, Any], dict[str, Any], MutableSequence[Callable[[type], type]]], None], Doc(' Processes class data before construction.\n\n            For use cases, such as argument conversion.\n        ')]], Doc(' Processors to apply before construction of class. ')] = (), postprocessors: Annotated[Sequence[Annotated[Callable[[type, MutableSequence[Callable[[type], type]]], None], Doc(' Processes class before decoration.\n\n            For use cases, such as decorator list manipulation.\n        ')]], Doc(' Processors to apply before decoration of class. ')] = ()) Annotated[Callable[[type, Annotated[Callable[[...], type], Doc(' Bound class constructor function.\n\n            Usually from ``super( ).__new__`` or a partial function.\n        ')], str, tuple[type, ...], dict[str, Any], Mapping[str, Any], Sequence[Callable[[type], type]]], type], Doc(' Constructor to use with metaclass. ')]

Produces constructors for classes.

classcore.factories.produce_class_initializer(attributes_namer: Callable[[str, str], str], completers: Annotated[Sequence[Annotated[Callable[[type], None], Doc(' Completes initialization of class.\n\n            For use cases, such as enabling immutability once all other\n            initialization has occurred.\n        ')]], Doc(' Processors to apply at final stage of class initialization. ')] = ()) Annotated[Callable[[type, Annotated[Callable[[...], None], Doc(' Bound initializer function.\n\n            Usually from ``super( ).__init__`` or a partial function.\n        ')], Sequence[Any], Mapping[str, Any]], None], Doc(' Initializer to use with metaclass. ')]

Produces initializers for classes.

Module classcore.factories

Factories which produce metaclass implementations.

classcore.factories.produce_class_constructor(attributes_namer: Callable[[str, str], str], preprocessors: Annotated[Sequence[Annotated[Callable[[type[type], str, list[type], dict[str, Any], dict[str, Any], MutableSequence[Callable[[type], type]]], None], Doc(' Processes class data before construction.\n\n            For use cases, such as argument conversion.\n        ')]], Doc(' Processors to apply before construction of class. ')] = (), postprocessors: Annotated[Sequence[Annotated[Callable[[type, MutableSequence[Callable[[type], type]]], None], Doc(' Processes class before decoration.\n\n            For use cases, such as decorator list manipulation.\n        ')]], Doc(' Processors to apply before decoration of class. ')] = ()) Annotated[Callable[[type, Annotated[Callable[[...], type], Doc(' Bound class constructor function.\n\n            Usually from ``super( ).__new__`` or a partial function.\n        ')], str, tuple[type, ...], dict[str, Any], Mapping[str, Any], Sequence[Callable[[type], type]]], type], Doc(' Constructor to use with metaclass. ')]

Produces constructors for classes.

classcore.factories.produce_class_initializer(attributes_namer: Callable[[str, str], str], completers: Annotated[Sequence[Annotated[Callable[[type], None], Doc(' Completes initialization of class.\n\n            For use cases, such as enabling immutability once all other\n            initialization has occurred.\n        ')]], Doc(' Processors to apply at final stage of class initialization. ')] = ()) Annotated[Callable[[type, Annotated[Callable[[...], None], Doc(' Bound initializer function.\n\n            Usually from ``super( ).__init__`` or a partial function.\n        ')], Sequence[Any], Mapping[str, Any]], None], Doc(' Initializer to use with metaclass. ')]

Produces initializers for classes.

Module classcore.exceptions

Exceptions from package.

exception classcore.exceptions.AttributeImmutability(name: str, target: str)

Bases: AttributeError, Omnierror

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

args
name

attribute name

obj

object

exception classcore.exceptions.BehaviorExclusionInvalidity(verifier: Any)

Bases: TypeError, ValueError, Omnierror

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

args
exception classcore.exceptions.ErrorProvideFailure(name: str, reason: str)

Bases: RuntimeError, Omnierror

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

args
exception classcore.exceptions.Omnierror(*args, **kwargs)

Bases: Exception, Omniexception

Base error for package.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

args
exception classcore.exceptions.Omniexception(*args, **kwargs)

Bases: BaseException, Object

Base exception for package.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

args

Module classcore.nomina

Catalog of common type aliases.

classcore.nomina.AttributesNamer

alias of Callable[[str, str], str]

classcore.nomina.DecorationPreparer

alias of Callable[[type, MutableSequence[Callable[[type], type]]], None]

classcore.nomina.DecorationPreparers

alias of Sequence[Callable[[type, MutableSequence[Callable[[type], type]]], None]]

classcore.nomina.Decorator

alias of Callable[[type], type]

classcore.nomina.Decorators

alias of Sequence[Callable[[type], type]]

classcore.nomina.DecoratorsMutable

alias of MutableSequence[Callable[[type], type]]

Module classcore.utilities

Various utilities for class manipulation.

classcore.utilities.describe_object(obj: object) str
classcore.utilities.getattr0(obj: object, name: str, default: Any) Any

Returns attribute from object without inheritance.

classcore.utilities.qualify_class_name(cls: type) str
classcore.utilities.repair_class_reproduction(original: type, reproduction: type) None

Repairs a class reproduction, if necessary.

Subpackage classcore.standard

Decorators and class factories which imbue concealment and immutability.

Concealment restricts the visibility of attributes on classes and their instances. By default, only public attributes (ones which do not start with _) are revealed for dir() calls. This behavior can be overriden by supplying visibility verifiers as a decorator factory argument or metaclass argument. These can be a sequence of attribute names, regular expression re.Pattern objects which match attribute names, or predicate functions which match attribute names. Or, total visibility (per the Python default) can be achieved by supplying visibles = '*' instead of a sequence of verifiers.

Immutability prevents assignment (including reassignment) or deletion of attrubtes on classes and their instances after they have been completely initialized. In addition to any standard Python class, this can be applied to dataclasses, allowing them to use __post_init__ to set attributes, which dataclasses.dataclass( frozen = True ) prevents. The immutability behavior can be overridden by supplying mutability verifiers as a decorator factory argument or metaclass argument. These behave similarly to the visibility verifiers described above.

Hooks to modify the concealment and immutability behaviors are also available.

Module classcore.standard.classes

Standard classes and class factories.

class classcore.standard.classes.Class(name: str, bases: tuple[type, ...], namespace: dict[str, Any], *, decorators: Sequence[Callable[[type], type]] = (), **arguments: Any)

Bases: type

mro()

Return a type’s method resolution order.

class classcore.standard.classes.Dataclass(name: str, bases: tuple[type, ...], namespace: dict[str, Any], *, decorators: Sequence[Callable[[type], type]] = (), **arguments: Any)

Bases: type

mro()

Return a type’s method resolution order.

class classcore.standard.classes.DataclassMutable(name: str, bases: tuple[type, ...], namespace: dict[str, Any], *, decorators: Sequence[Callable[[type], type]] = (), **arguments: Any)

Bases: type

mro()

Return a type’s method resolution order.

class classcore.standard.classes.DataclassObject

Bases: object

class classcore.standard.classes.DataclassObjectMutable

Bases: object

class classcore.standard.classes.DataclassProtocol(*args, **kwargs)

Bases: Protocol

class classcore.standard.classes.DataclassProtocolMutable(*args, **kwargs)

Bases: Protocol

class classcore.standard.classes.Object(*args, **kwargs)

Bases: object

class classcore.standard.classes.ObjectMutable(*args, **kwargs)

Bases: object

class classcore.standard.classes.Protocol(*args, **kwargs)

Bases: Protocol

class classcore.standard.classes.ProtocolClass(name: str, bases: tuple[type, ...], namespace: dict[str, Any], *, decorators: Sequence[Callable[[type], type]] = (), **arguments: Any)

Bases: _ProtocolMeta

mro()

Return a type’s method resolution order.

register(subclass)

Register a virtual subclass of an ABC.

Returns the subclass, to allow usage as a class decorator.

class classcore.standard.classes.ProtocolDataclass(name: str, bases: tuple[type, ...], namespace: dict[str, Any], *, decorators: Sequence[Callable[[type], type]] = (), **arguments: Any)

Bases: _ProtocolMeta

mro()

Return a type’s method resolution order.

register(subclass)

Register a virtual subclass of an ABC.

Returns the subclass, to allow usage as a class decorator.

class classcore.standard.classes.ProtocolDataclassMutable(name: str, bases: tuple[type, ...], namespace: dict[str, Any], *, decorators: Sequence[Callable[[type], type]] = (), **arguments: Any)

Bases: _ProtocolMeta

mro()

Return a type’s method resolution order.

register(subclass)

Register a virtual subclass of an ABC.

Returns the subclass, to allow usage as a class decorator.

class classcore.standard.classes.ProtocolMutable(*args, **kwargs)

Bases: Protocol

Module classcore.standard.decorators

Standard decorators.

classcore.standard.decorators.dataclass_with_standard_behaviors(decorators: ~collections.abc.Sequence[~collections.abc.Callable[[type], type]] = (), mutables: ~collections.abc.Sequence[str | ~re.Pattern[str] | ~collections.abc.Callable[[str], bool]] | ~typing.Literal['*'] = (), visibles: ~collections.abc.Sequence[str | ~re.Pattern[str] | ~collections.abc.Callable[[str], bool]] | ~typing.Literal['*'] = (<function is_public_identifier>,)) Callable[[type], type]

Dataclass decorator factory.

classcore.standard.decorators.decoration_by(*decorators: Callable[[type], type], preparers: Sequence[Callable[[type, MutableSequence[Callable[[type], type]]], None]] = ()) Callable[[type], type]

Class decorator which applies other class decorators.

Useful to apply a stack of decorators as a sequence.

Can optionally execute a sequence of decoration preparers before applying the decorators proper. These can be used to alter the decorators list itself, such as to inject decorators based on introspection of the class.

classcore.standard.decorators.prepare_dataclass_for_instances(cls: type, decorators: MutableSequence[Callable[[type], type]], /, *, attributes_namer: Callable[[str, str], str]) None

Annotates dataclass in support of instantiation machinery.

classcore.standard.decorators.produce_attributes_assignment_decorator(level: str, attributes_namer: Callable[[str, str], str], error_class_provider: Callable[[str], type[Exception]], implementation_core: AssignerCore) Callable[[type], type]
classcore.standard.decorators.produce_attributes_deletion_decorator(level: str, attributes_namer: Callable[[str, str], str], error_class_provider: Callable[[str], type[Exception]], implementation_core: DeleterCore) Callable[[type], type]
classcore.standard.decorators.produce_attributes_surveillance_decorator(level: str, attributes_namer: Callable[[str, str], str], implementation_core: SurveyorCore) Callable[[type], type]
classcore.standard.decorators.produce_class_construction_decorator(attributes_namer: Callable[[str, str], str], constructor: Annotated[Callable[[type, Annotated[Callable[[...], type], Doc(' Bound class constructor function.\n\n            Usually from ``super( ).__new__`` or a partial function.\n        ')], str, tuple[type, ...], dict[str, Any], Mapping[str, Any], Sequence[Callable[[type], type]]], type], Doc(' Constructor to use with metaclass. ')]) Callable[[type], type]

Produces metaclass decorator to control class construction.

Decorator overrides __new__ on metaclass.

classcore.standard.decorators.produce_class_factory_decorators(attributes_namer: ~collections.abc.Callable[[str, str], str] = <function calculate_attrname>, error_class_provider: ~collections.abc.Callable[[str], type[Exception]] = <function provide_error_class>, assigner_core: ~classcore.standard.nomina.AssignerCore = <function assign_attribute_if_mutable>, deleter_core: ~classcore.standard.nomina.DeleterCore = <function delete_attribute_if_mutable>, surveyor_core: ~classcore.standard.nomina.SurveyorCore = <function survey_visible_attributes>) Sequence[Callable[[type], type]]
classcore.standard.decorators.produce_class_initialization_decorator(attributes_namer: Callable[[str, str], str], initializer: Annotated[Callable[[type, Annotated[Callable[[...], None], Doc(' Bound initializer function.\n\n            Usually from ``super( ).__init__`` or a partial function.\n        ')], Sequence[Any], Mapping[str, Any]], None], Doc(' Initializer to use with metaclass. ')]) Callable[[type], type]

Produces metaclass decorator to control class initialization.

Decorator overrides __init__ on metaclass.

classcore.standard.decorators.produce_decoration_preparers_factory(attributes_namer: ~collections.abc.Callable[[str, str], str] = <function calculate_attrname>, error_class_provider: ~collections.abc.Callable[[str], type[Exception]] = <function provide_error_class>, class_preparer: ~classcore.standard.nomina.ClassPreparer | None = None) Callable[[], Sequence[Callable[[type, MutableSequence[Callable[[type], type]]], None]]]
classcore.standard.decorators.produce_decorators_factory(level: str, attributes_namer: ~collections.abc.Callable[[str, str], str] = <function calculate_attrname>, error_class_provider: ~collections.abc.Callable[[str], type[Exception]] = <function provide_error_class>, assigner_core: ~classcore.standard.nomina.AssignerCore = <function assign_attribute_if_mutable>, deleter_core: ~classcore.standard.nomina.DeleterCore = <function delete_attribute_if_mutable>, surveyor_core: ~classcore.standard.nomina.SurveyorCore = <function survey_visible_attributes>) Callable[[Sequence[str | Pattern[str] | Callable[[str], bool]] | Literal['*'], Sequence[str | Pattern[str] | Callable[[str], bool]] | Literal['*']], Sequence[Callable[[type], type]]]
classcore.standard.decorators.produce_instances_initialization_decorator(attributes_namer: Callable[[str, str], str], mutables: Sequence[str | Pattern[str] | Callable[[str], bool]] | Literal['*'], visibles: Sequence[str | Pattern[str] | Callable[[str], bool]] | Literal['*']) Callable[[type], type]
classcore.standard.decorators.with_standard_behaviors(decorators: ~collections.abc.Sequence[~collections.abc.Callable[[type], type]] = (), mutables: ~collections.abc.Sequence[str | ~re.Pattern[str] | ~collections.abc.Callable[[str], bool]] | ~typing.Literal['*'] = (), visibles: ~collections.abc.Sequence[str | ~re.Pattern[str] | ~collections.abc.Callable[[str], bool]] | ~typing.Literal['*'] = (<function is_public_identifier>,)) Callable[[type], type]

Class decorator factory.

Module classcore.standard.modules

Standard module classes and reclassifers.

class classcore.standard.modules.Module(*args, **kwargs)

Bases: ModuleType, Object

Modules with attributes immutability and concealment.

classcore.standard.modules.reclassify_modules(attributes: ~types.Annotated[~collections.abc.Mapping[str, ~typing_extensions.Any] | ~types.ModuleType | str, Doc('Module, module name, or dictionary of object attributes.')], /, *, attributes_namer: ~collections.abc.Annotated[~collections.abc.Callable[[str, str], str], Doc(' Attributes namer function with which to seal class. ')] = <function calculate_attrname>, recursive: ~typing.Annotated[bool, Doc('Recursively reclassify package modules?')] = False) None

Reclassifies modules to have attributes concealment and immutability.

Can operate on individual modules or entire package hierarchies.

Notes

  • Only converts modules within the same package to prevent unintended modifications to external modules.

  • When used with a dictionary, converts any module objects found as values if they belong to the same package.

  • Has no effect on already-reclassified modules.

Module classcore.standard.behaviors

Implementations for standard behaviors.

classcore.standard.behaviors.assign_attribute_if_mutable(obj: object, /, *, ligation: Annotated[Callable[[str, Any], None], Doc(' Bound attributes assigner function.\n\n            Usually from ``super( ).__setattr__`` or a partial function.\n        ')], attributes_namer: Callable[[str, str], str], error_class_provider: Callable[[str], type[Exception]], level: str, name: str, value: Any) None
classcore.standard.behaviors.classify_behavior_exclusion_verifiers(verifiers: Sequence[str | Pattern[str] | Callable[[str], bool]]) tuple[Set[str], Sequence[Pattern[str]], Sequence[Callable[[str], bool]]]
classcore.standard.behaviors.delete_attribute_if_mutable(obj: object, /, *, ligation: Annotated[Callable[[str], None], Doc(' Bound attributes deleter function.\n\n            Usually from ``super( ).__delattr__`` or a partial function.\n        ')], attributes_namer: Callable[[str, str], str], error_class_provider: Callable[[str], type[Exception]], level: str, name: str) None
classcore.standard.behaviors.produce_class_construction_postprocessor(attributes_namer: Callable[[str, str], str]) Annotated[Callable[[type, MutableSequence[Callable[[type], type]]], None], Doc(' Processes class before decoration.\n\n            For use cases, such as decorator list manipulation.\n        ')]
classcore.standard.behaviors.produce_class_construction_preprocessor(attributes_namer: Callable[[str, str], str]) Annotated[Callable[[type[type], str, list[type], dict[str, Any], dict[str, Any], MutableSequence[Callable[[type], type]]], None], Doc(' Processes class data before construction.\n\n            For use cases, such as argument conversion.\n        ')]
classcore.standard.behaviors.produce_class_initialization_completer(attributes_namer: Callable[[str, str], str]) Annotated[Callable[[type], None], Doc(' Completes initialization of class.\n\n            For use cases, such as enabling immutability once all other\n            initialization has occurred.\n        ')]
classcore.standard.behaviors.record_behavior(cls: type, /, *, attributes_namer: Callable[[str, str], str], level: str, basename: str, label: str, behaviors: set[str], verifiers: Sequence[str | Pattern[str] | Callable[[str], bool]] | Literal['*']) None
classcore.standard.behaviors.record_class_construction_arguments(attributes_namer: Callable[[str, str], str], namespace: dict[str, Any], arguments: dict[str, Any]) None
classcore.standard.behaviors.survey_visible_attributes(obj: object, /, *, ligation: Annotated[Callable[[], Iterable[str]], Doc(' Bound attributes surveyor function.\n\n            Usually from ``super( ).__dir__`` or a partial function.\n        ')], attributes_namer: Callable[[str, str], str], level: str) Iterable[str]

Module classcore.standard.nomina

Catalog of common type aliases.

class classcore.standard.nomina.AssignerCore(*args, **kwargs)

Bases: Protocol

Core implementation of attributes assigner.

classcore.standard.nomina.AttributesNamer

alias of Callable[[str, str], str]

classcore.standard.nomina.BehaviorExclusionNames

alias of Set[str]

classcore.standard.nomina.BehaviorExclusionPredicate

alias of Callable[[str], bool]

classcore.standard.nomina.BehaviorExclusionPredicates

alias of Sequence[Callable[[str], bool]]

classcore.standard.nomina.BehaviorExclusionRegex

alias of Pattern[str]

classcore.standard.nomina.BehaviorExclusionRegexes

alias of Sequence[Pattern[str]]

classcore.standard.nomina.BehaviorExclusionVerifiers

alias of Sequence[str | Pattern[str] | Callable[[str], bool]]

class classcore.standard.nomina.ClassPreparer(*args, **kwargs)

Bases: Protocol

Prepares class for decorator application.

classcore.standard.nomina.DecorationPreparer

alias of Callable[[type, MutableSequence[Callable[[type], type]]], None]

classcore.standard.nomina.DecorationPreparers

alias of Sequence[Callable[[type, MutableSequence[Callable[[type], type]]], None]]

classcore.standard.nomina.Decorator

alias of Callable[[type], type]

classcore.standard.nomina.Decorators

alias of Sequence[Callable[[type], type]]

classcore.standard.nomina.DecoratorsMutable

alias of MutableSequence[Callable[[type], type]]

class classcore.standard.nomina.DeleterCore(*args, **kwargs)

Bases: Protocol

Core implementation of attributes deleter.

classcore.standard.nomina.ErrorClassProvider

alias of Callable[[str], type[Exception]]

class classcore.standard.nomina.SurveyorCore(*args, **kwargs)

Bases: Protocol

Core implementation of attributes surveyor.