Skip to content

Instantly share code, notes, and snippets.

@dutc
Created October 20, 2022 17:33
Show Gist options
  • Save dutc/d11723b13dd2e7c373e9a5d0200fdb39 to your computer and use it in GitHub Desktop.
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)
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