Skip to content

Instantly share code, notes, and snippets.

@Tishka17
Created June 9, 2024 08:42
Show Gist options
  • Save Tishka17/4211bbad90449a72c1a2908393aebcea to your computer and use it in GitHub Desktop.
Save Tishka17/4211bbad90449a72c1a2908393aebcea to your computer and use it in GitHub Desktop.
Converting between types using adaptix parsers
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