Last active
January 15, 2024 17:43
-
-
Save d-v-b/888e5f3e4097423e0ceb23957b72c81e to your computer and use it in GitHub Desktop.
This file contains 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
""" | |
Demo of TypedDict for payloads for a method on a dataclass that returns a new instance with updated attributes. | |
""" | |
from dataclasses import dataclass | |
from typing import TypedDict | |
class FooUpdate(TypedDict): | |
prop_a: int | |
prop_b: str | |
prop_c: list[str] | |
@dataclass | |
class Foo: | |
prop_a: int | |
prop_b: str | |
prop_c: list[str] | |
def evolve(self, update: FooUpdate): | |
return self.__class__( | |
prop_a = update.get('prop_a', self.prop_a), | |
prop_b = update.get('prop_b', self.prop_b), | |
prop_c = update.get('prop_c', self.prop_c) | |
) | |
class FooChildUpdate(TypedDict): | |
prop_a: int | |
class FooChild(Foo): | |
def evolve(self, update: FooChildUpdate): | |
return self.__class__( | |
prop_a = update.get('prop_a', self.prop_a), | |
prop_b = self.prop_b, | |
prop_c = self.prop_c) | |
f = Foo(prop_a = 10, prop_b = 'str', prop_c = ['hi']) | |
f_evolved = f.evolve(update={'prop_a': 11}) | |
fc = FooChild(prop_a=10, prop_b='str', prop_c = ['hi']) | |
fc_evolved = fc.evolve(update={'prop_a': 100}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment