Created
June 9, 2024 08:42
-
-
Save Tishka17/4211bbad90449a72c1a2908393aebcea to your computer and use it in GitHub Desktop.
Converting between types using adaptix parsers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from dataclasses import dataclass | |
from adaptix import Retort, Chain, loader, dumper | |
@dataclass | |
class A: | |
field: str | |
class CustomA: | |
def __init__(self, **kwargs): | |
self.field = kwargs.get("field") | |
def __eq__(self, other): | |
return type(other) == type(self) and self.field == other.field | |
class MyDict: | |
def __init__(self, obj): | |
self.obj = obj | |
def __getitem__(self, name): | |
return getattr(self.obj, name) | |
retort = Retort( | |
recipe=[ | |
loader(A, MyDict, Chain.FIRST), | |
dumper(A, lambda x: CustomA(**x), Chain.LAST) | |
] | |
) | |
a = A(field="value") | |
ca = CustomA(field="value") | |
assert ca == retort.dump(a) | |
assert a == retort.load(ca, A) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment