dataclassbase package#

Module contents#

class dataclassbase.BasicFieldProvider(field_factory: ~dataclassbase.FieldFactory = <class 'dataclassbase.Field'>, external_field_validator: ~dataclassbase._util.E[type[TField] | ~typing.Callable[[~dataclassbase.Field], TField]] = Ellipsis)#

Bases: FieldProvider, Generic

Implements a basic mechanism for handling the creation and override behavior of fields.

check_overrides(base_fields: MappingProxyType, cls_fields: MappingProxyType) None#

Checks whether a combination of base and child fields are valid.

By default, this method uses the Field.check_overriding_field() and Field.check_overridden_field() methods of Field.

Parameters:
  • base_fields – The fields of the base. These are the fields that get overridden.

  • cls_fields – The fields of the child. These are the fields that override the base fields.

create_field_override(original: Field) TField#

Creates a new field from an original field declared on a base class.

Parameters:

original – The original field.

Returns:

The new field.

instantiate_field(name: str, annotation: Any, declaration: FieldDeclaration[P, TField]) TField#

Instantiates a field from a field declaration.

Parameters:
  • name – The name of the field.

  • annotation – The annotation of the field.

  • declaration – Additional parameters to supply to the field type.

Returns:

The instantiated field.

make_field(name: str, annotation: Any, has_default: bool, default: Any) TField#

Initializes a new field.

Parameters:
  • name – The name of the field.

  • annotation – The annotation the field was declared with.

  • has_default – Indicates whether the field has a default value or not.

  • default – The default value of the field.

Returns:

The field created for the given parameters.

class dataclassbase.BehaviorModifier#

Bases: ABC

An abstract base class defining a mechanism for changing the behavior of a dataclass and its instances.

abstractmethod modify(cls: type[DataclassType]) None#
class dataclassbase.ConstructorlessFactory(*args, **kwargs)#

Bases: Protocol, Generic

A protocol that is used to declare functions that may take zero parameters.

class dataclassbase.DataclassMeta(name: str, bases: tuple[type, ...], dct: dict[str, Any])#

Bases: DataclassMetaBase, Generic

Provides a basic Field-based metaclass. When used as a metaclass, the class and any subclass inherit a dataclass-like behavior. See DataclassMetaBase and make_dataclass() for further information.

class dataclassbase.DataclassMetaBase(name: str, bases: tuple[type, ...], dct: dict[str, Any])#

Bases: type, Generic

A base class for metaclasses inducing dataclass-like behavior. The make_dataclass() gets invoked on subclasses.

Note that this class is not intended to be used directly as a metaclass. The typing.dataclass_transform() method is not applied to the current type since it requires specific field specifiers. In derived classes, however, the field specifiers may not be limited to the Field-class. Therefore, you should define a metaclass that is derived from the DataclassMetaBase class if you want to define a class with custom field specifiers and add a typing.dataclass_transform()-decoration to them. Use the _field_provider() to control the conversion of the field specifies into fields.

class dataclassbase.DataclassType(*args: Any, **kwargs: Any)#

Bases: Protocol

A protocol that describes the members of dataclass-like classes.

class dataclassbase.DataclassbaseInstance(*args, **kwargs)#

Bases: Protocol

A protocol that describes the instances of the dataclass-like classes created by this module via make_dataclass(), etc.

class dataclassbase.Equatable(fields_only: bool = True, override_hash: bool = True, override_eq: bool = True)#

Bases: BehaviorModifier

Used to add equality and inequality operators to the dataclasses.

property fields_only: bool#

Determines whether only the fields or all attributes are to be considered by the equality and inequality operators and the hash function, if provided.

Returns:

True if only the fields, False if all attributes get considered.

modify(cls: type[DataclassType]) None#

Implements, if demanded, the equality and inequality operator and the hash function for the indicated type.

Parameters:

cls – The type whose behavior to override.

property override_eq: bool#

Determines whether the current instance implements the equality and inequality operators. See __init__() for further information.

Returns:

True if the equality and inequality operators get implemented, False if not.

property override_hash: bool#

Determines whether the current instance implements __hash__(). See __init__() for further information.

Returns:

True if an implementation for __hash__() is generated, False if not.

class dataclassbase.Field(name: str, annotation: Any, has_default: bool = False, default: Any = None, default_factory: Callable[[], None] | None = None)#

Bases: object

A class that describes a field of a dataclass-like class.

See make_dataclass() for instructions of how to use subclasses of Field to further constrain and modify fields. Any member of instances of derived subclasses should be intended to be immutable.

property annotation: Any#

The annotation hinting at the type of field.

Returns:

The annotation.

check_assignment(obj: Any) None#

In derived classes, this checks whether an assignment obj to the current field is suitable for the class.

By convention, the function must raise either a TypeError or a ValueError for invalid values.

Parameters:

obj – The assignment made to the current field.

check_overridden_field(overridden_field: Field) None#

In derived classes, this checks whether the current field can override another field.

In combination with check_overriding_field(), this provides a mechanism ensuring integrity on derived fields.

By convention, the function must raise either a TypeError or a ValueError for invalid values.

Parameters:

overridden_field – The field to be overridden.

check_overriding_field(overriding_field: Field) None#

In derived classes, this checks whether a field override overriding the current field is valid. This can, for example, be used to ensure that an overriding field allows only assignments that are also accepted by the current instance.

In combination with check_overridden_field(), this provides a mechanism ensuring integrity on derived fields.

By convention, the function must raise either a TypeError or a ValueError for invalid values.

Parameters:

overriding_field – The field that is to override the current instance.

classmethod declare(*args: P, **kwargs: P) FieldDeclaration[P, TField]#

Declares, but does not fully initialize a field. The field will be instantiated when the dataclass gets built.

Use this function to explicitly specify a field instance instead of letting it get initialized implicitly.

Example: >>> class Dataclass(DataclassMeta): … x: list = Field.declare(default_factory=list)

Parameters:
  • args – Positional arguments to supply to __factory after the values for name and annotation.

  • kwargs – Additional keyword arguments to supply to __factory.

Returns:

The generated field declaration.

property default: Any#

If has_default() is set to True, this provides a constant default value unless default_factory() is not None.

See has_default() for further information.

Returns:

None if has_default() is False or default_factory() is set to a value different from None. Otherwise, this provides a constant default value.

property default_factory: Callable[[], Any] | None#

If has_default() is set to True, this may provide a factory responsible for the generation of default values.

See has_default() for further information.

Returns:

None if either has_default() is False or default() provides a constant default value, or, otherwise, a factory function generating a default value.

property has_default: bool#

Indicates whether the current field has a constant default value indicated via default_factory() or a default value factory indicated via default_factory(). If has_default() is True, either default_factory() is not None, implying that the default_factory() provides the default value, or default() is to be used as the default value.

Returns:

A value indicating whether the current field has a default value.

property name: str#

The name of the field.

Returns:

The name.

class dataclassbase.FieldDeclaration(_FieldDeclaration__factory: FieldInitializer[P, TField], /, *args: P, **kwargs: P)#

Bases: Generic[P, TField]

Declares, but does not fully initialize a field. The field will be instantiated when the dataclass gets built.

class dataclassbase.FieldFactory(*args, **kwargs)#

Bases: Protocol, Generic

A protocol that behaves similar to the factory represented by the Field type.

class dataclassbase.FieldInitializer(*args, **kwargs)#

Bases: Protocol, Generic[P, TField]

A generic factory that creates a new field from a name, an annotation, and additional parameters defined via the signature defined via P.

Any such initializer must take the name and annotation as its first two positional arguments.

class dataclassbase.FieldProvider#

Bases: ABC, Generic

Defines an abstract class for handling the creation and override behavior of fields.

abstractmethod check_overrides(base_fields: MappingProxyType, cls_fields: MappingProxyType) None#

Checks whether a combination of base and child fields are valid.

By default, this method uses the Field.check_overriding_field() and Field.check_overridden_field() methods of Field.

Parameters:
  • base_fields – The fields of the base. These are the fields that get overridden.

  • cls_fields – The fields of the child. These are the fields that override the base fields.

gather_fields(cls: type) dict[str, TField]#

Gathers the dataclass fields of a class.

Parameters:

cls – The class from which to determine the fields.

Returns:

The mapping of field names to fields.

class dataclassbase.Frozen(fields_only: bool = True)#

Bases: BehaviorModifier

Used to make dataclass fields immutable.

property fields_only: bool#

Indicates whether the current class freezes only fields or all attributes.

Returns:

True if only fields, False if all attributes get frozen.

modify(cls: type[DataclassType]) None#

Makes the indicated dataclass frozen, i.e., after initialization, its fields may no longer be changed.

Parameters:

cls – The class to freeze.

class dataclassbase.KeywordOnly#

Bases: BehaviorModifier

Enforces that the parameters supplied to a dataclass are indicated via keyword.

modify(cls: type[DataclassType]) None#

Modifies the initializer of the indicated class to allow only keyword arguments.

Parameters:

cls – The dataclass to modify.

class dataclassbase.ObjectHandler#

Bases: Generic

Handles the initialization and set-attribute behavior of a dataclass-like object.

handle_delete_attribute(obj: Any, field: Field | None, name: str, inner_delete_attribute: Callable[[Any, str], None] | None) None#

This method gets called when __delattr__ is invoked for an object.

Parameters:
  • obj – The object on which the attribute gets deleted.

  • field – The field whose attribute gets deleted.

  • name – The name of the attribute of the field.

  • inner_delete_attribute – The original __delattr__-procedure, if there was one; None otherwise.

handle_set_attribute(obj: Any, field: Field | None, name: str, value: Any, inner_set_attribute: Callable[[Any, str, Any], None] | None) None#

This method gets called when __setattr__ is invoked for an object.

Parameters:
  • obj – The object for which to set the field’s value.

  • field – The field that gets assigned a new value. If the attribute does not correspond to a field, this value is None.

  • name – The name of the attribute to which the new value is assigned.

  • value – The new value to assign to the attribute.

  • inner_set_attribute – The original __setattr__-procedure, if there was one; None otherwise.

init_instance(cls: DataclassType, obj: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) None#

Initializes the instance given positional and keyword arguments. The positional and keyword arguments get mapped to their respective fields.

This method gets called during the __init__ method call of obj.

Parameters:
  • cls – The class of the object to initialize.

  • obj – The object to initialize.

  • args – The positional arguments.

  • kwargs – The keyword arguments.

property override_delete_attribute: bool#

Indicates whether the __delattr_ behavior is to be overridden to route the handle_delete_attribute()-method. Defaults to True.

Typically, delete-attribute gets overridden to prevent users from deleting attributes from the dataclasses. :return: True if __delattr__ is to be overridden, False otherwise.

property override_set_attribute: bool#

Indicates whether the __setattr__ behavior is to be overridden to route to the handle_set_attribute()-method. Defaults to True.

Typically, set-attribute gets overridden, since assignments to fields need be checked. In some cases, however, this behavior may not be required (e.g., if the dataclass is to be frozen, anyway).

Returns:

True if __setattr__ is to be overridden, False otherwise.

class dataclassbase.PositionalOnly#

Bases: BehaviorModifier

Enforces that the parameters supplied to a dataclass are indicated via position.

modify(cls: type[DataclassType]) None#

Modifies the initializer of the indicated class to allow only positional arguments.

Parameters:

cls – The dataclass to modify.

class dataclassbase.Representable(obj_as_dict: E[Callable[[DataclassbaseInstance], Any]] = Ellipsis, dict_to_str: E[Callable[[DataclassbaseInstance, dict[str, Any]], str]] | None = Ellipsis, dict_to_repr: E[Callable[[DataclassbaseInstance, dict[str, Any]], str]] | None = Ellipsis)#

Bases: BehaviorModifier

Used to add functionality for string representation (str()) and object representation (repr()) to the dataclass.

modify(cls: type[DataclassType]) None#

Overrides __str__() and/or __repr__() according to the behavior defined during initialization.

Parameters:

cls – The class to modify.

class dataclassbase.TypeConstrainedField(name: str, annotation: Any, has_default: bool = False, default: Any = None, default_factory: Callable[[], None] | None = None)#

Bases: Field

A field that can be used to provide simple isinstance-based type checking using the field’s annotation.

The annotation must provide an __instancecheck__ to perform assignment checks. Note that the instance check gets invoked once with None during initialization to eliminate the .

check_assignment(obj: Any) None#

In derived classes, this checks whether an assignment obj to the current field is suitable for the class.

By convention, the function must raise either a TypeError or a ValueError for invalid values.

Parameters:

obj – The assignment made to the current field.

dataclassbase.as_dict(obj: DataclassbaseInstance, child_dataclass_to_dict: E[Callable[[DataclassbaseInstance], Any]] | None = Ellipsis, fields_only: bool = True) dict[str, Any]#

Builds a dictionary from the fields of the indicated dataclass instance.

Parameters:
  • obj – The dataclass instance to build the dictionary from.

  • child_dataclass_to_dict – A function to call for child dataclasses.

  • fields_only – If True, only fields of the dataclass are added to the dictionary. Otherwise, all attributes get processed.

Returns:

The dictionary of fields or attributes.

dataclassbase.dataclass(*modifiers: BehaviorModifier | ConstructorlessFactory[BehaviorModifier], field_provider: E[FieldProvider | FieldFactory] = Ellipsis, object_handler: E[ObjectHandler] = Ellipsis) Callable[[TCls], TCls]#

Returns a function that that makes the classes supplied to it dataclass-like. The classes must not be dataclasses, yet.

Intended to be used as a decorator.

Parameters:
  • field_provider – A field provider used to initialize the fields of the dataclass. Depending on the type of field provider, fields may expose different types of behavior during initialization and attribute assignment.

  • object_handler – Implements the initialization and attribute assignment of instances of the dataclass.

  • modifiers – Additional modifiers changing the behavior of the dataclass.

dataclassbase.field(__cls: P, TField]=<class 'dataclassbase.Field'>, /, *args: P, **kwargs: P) FieldDeclaration[P, TField]#

Declares, but does not fully initialize a field. The field will be instantiated when the dataclass gets built.

Use this function to explicitly specify a field instance instead of letting it get initialized implicitly. For derived field types, consider Field.declare().

Example: >>> class Dataclass(DataclassMeta): … x: list = field(default_factory=list)

Parameters:
  • __cls – The field type or, more general, a factory that generates the field.

  • args – Positional arguments to supply to __factory after the values for name and annotation.

  • kwargs – Additional keyword arguments to supply to __factory.

Returns:

The generated field declaration.

dataclassbase.make_dataclass(cls: type, field_provider: E[FieldProvider | FieldFactory] = Ellipsis, object_handler: E[ObjectHandler] = Ellipsis, modifiers: tuple[BehaviorModifier | ConstructorlessFactory[BehaviorModifier], ...] = ()) None#

Makes the indicated class dataclass-like. The class must not be a dataclass, yet.

Parameters:
  • cls – The class to make a dataclass.

  • field_provider – A field provider used to initialize the fields of the dataclass. Depending on the type of field provider, fields may expose different types of behavior during initialization and attribute assignment.

  • object_handler – Implements the initialization and attribute assignment of instances of the dataclass.

  • modifiers – Additional modifiers changing the behavior of the dataclass.