Library that lets you define abstract properties for dataclasses.
Project description
Dataclass ABC
Library that lets you define abstract properties for dataclasses.
Installation
pip install dataclass-abc
Usage
The dataclass_abc
class decorator:
- erases the default value of the fields (see comment below)
- resolves the abstract properties overwritten by a field
from abc import ABC, abstractmethod
from dataclass_abc import dataclass_abc
class A(ABC):
@property
@abstractmethod
def val(self) -> str:
...
@dataclass_abc
class B(A):
val: str # overwrites the abstract property 'val' in 'A'
Erase default value
dataclass_abc
erases the default values of fields. This has the advantage that
additional fields that do not refer to an abstract property can be added
without running into the "non-default argument follows default argument"
exception.
Therefore, do not define default values, work with initialize functions instead (see Design Pattern below).
from abc import ABC, abstractmethod
from dataclass_abc import dataclass_abc
class A(ABC):
@property
@abstractmethod
def val1(self) -> str:
...
@dataclass_abc
class B(A):
val1: str
val2: str
# work with initialize functions when dealing with default values
def init_b(
val1: str,
val2: str = 'default',
):
return B(val1=val1, val2=val2)
Example
The example implements the code snippets taken from RealPython with abstract properties.
Design pattern
This library suggests the design pattern as implemented in the example:
- mixins - a mixin is an abstract class that implements data as abstract properties and methods based on the abstract properties.
- classes - an abstract class inherits from one or more mixins
(see
City
orCapitalCity
in the example). This class is used for pattern matching, e.g. usingisinstance
method. - impl - an implementation class implements the abstract properties.
(see
CityImpl
orCapitalCityImpl
in the example). This class is decorated withdataclass_abc
andresolve_abc_prop
and should always be called through an initialize function. - init - an initialize function (or constructor function) initializes an implementation class.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for dataclass_abc-0.0.3-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | a6b9a67379755812d3f2990221b9d783be1d0a2dbfe2d700ddb7d07b4db54979 |
|
MD5 | f0fe45ed8d29ab56ce4f933aada688b4 |
|
BLAKE2b-256 | e30ef71ccea55c7d479316df583a6e03275a6f71d6eff728cd9b64f075dc7ea5 |