Created
October 20, 2022 17:33
-
-
Save dutc/d11723b13dd2e7c373e9a5d0200fdb39 to your computer and use it in GitHub Desktop.
Legitimately Bad Idea (defining data model methods using instance-level modalities via `__class__`-patching)
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
from dataclasses import dataclass | |
@dataclass | |
class Ctx: | |
mode : bool = True | |
def __post_init__(self): | |
if (mode := self.mode): | |
cls = type(self) | |
self.__class__ = type( | |
f'fake_{cls.__name__}', | |
cls.__mro__, | |
{ | |
**cls.__dict__, | |
'__exit__': lambda *_: print(f'{mode = }'), | |
} | |
) | |
__enter__ = lambda s: s | |
__exit__ = lambda s, *_: None | |
with Ctx(mode=False) as obj: | |
print(f'{obj = }') | |
with Ctx(mode=True) as obj: | |
print(f'{obj = }') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment