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 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 name(self) -> str:
...
@dataclass_abc(frozen=True)
class B(A):
name: str # overwrites the abstract property 'name' in 'A'
Define mutable variables
Define a mutable variable name
in the abstract class A
by using the
name.setter
decorator.
from abc import ABC, abstractmethod
from dataclass_abc import dataclass_abc
class A(ABC):
@property
@abstractmethod
def name(self) -> str:
...
@name.setter
@abstractmethod
def name(self, val: str):
...
def set_name(self, val: str):
self.name = val
@dataclass_abc
class B(A):
name: str
b = B(name='A')
b.set_name('B')
Example
The example implements the code snippets taken from RealPython with abstract properties.
Design pattern
This library suggests the following design pattern:
- 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
dataclass_abc-0.0.5.tar.gz
(7.3 kB
view hashes)
Built Distribution
Close
Hashes for dataclass_abc-0.0.5-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | c6275a1ae0f651434e75b8ba45a051eff6844f2b606f8a24e0ad6d56019a3e09 |
|
MD5 | 8e8b163fb98b3cf51c5b9acc23201d71 |
|
BLAKE2b-256 | 20889291e386a8b166973a84ebd37a178b4a2d926753f792e8aa8fb5ca252f4f |