Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from inspect import Signature, Parameter
- def r_dataclass(cls):
- # grab the annotation dict
- ann = cls.__annotations__
- # make a signature out of the keys of annotation dict
- signature = Signature([Parameter(field, Parameter.POSITIONAL_OR_KEYWORD) for field in ann])
- # define __init__ that is injected
- def __init__(self, *args, **kwargs):
- #bind the signature to arguments of constructor
- bounded = signature.bind(*args, **kwargs)
- for key, val in bounded.arguments.items():
- # set the key and value in the instance of give class
- setattr(self, key, val)
- setattr(cls, '__init__', __init__)
- return cls
- # the way you use it
- @r_dataclass
- class Vector:
- x: float
- y: float
- @r_dataclass
- class Person:
- name: str
- age: int
- if __name__ == '__main__':
- v = Vector(3.0, 4.3)
- print(v.x, v.y)
Add Comment
Please, Sign In to add comment