Created
January 12, 2025 21:17
-
-
Save vkbo/fe9fb4c8d55b2f8f4bbfecd95284ef39 to your computer and use it in GitHub Desktop.
Simple dataclass that auto-implements slots
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 typing import TypeVar | |
T_ = TypeVar("T_", bound=object) | |
def myDataClass(cls: T_) -> T_: | |
"""A simple data class decorator that generates slots automatically | |
and creates an init function to match. | |
""" | |
def wrap(cls: T_) -> T_: | |
fields = tuple(a for a in dir(cls) if not a.startswith("__")) | |
values = {a: getattr(cls, a) for a in fields} | |
def init(self: T_) -> None: | |
nonlocal values | |
for a, v in values.items(): | |
setattr(self, a, v) | |
return type(cls.__class__.__name__, (object,), { # type: ignore | |
"__slots__": fields, "__init__": init | |
}) | |
return wrap(cls) | |
# With this decorator, the following class: | |
@myDataClass | |
class A: | |
one = 1 | |
two = "2" | |
# Becomes: | |
class B: | |
__slots__ = ("one", "two") | |
def __init__(self) -> None: | |
self.one = 1 | |
self.two = "2" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment