Guest User

Untitled

a guest
Apr 16th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.83 KB | None | 0 0
  1. from inspect import Signature, Parameter
  2.  
  3. def r_dataclass(cls):
  4. # grab the annotation dict
  5. ann = cls.__annotations__
  6. # make a signature out of the keys of annotation dict
  7. signature = Signature([Parameter(field, Parameter.POSITIONAL_OR_KEYWORD) for field in ann])
  8. # define __init__ that is injected
  9. def __init__(self, *args, **kwargs):
  10. #bind the signature to arguments of constructor
  11. bounded = signature.bind(*args, **kwargs)
  12. for key, val in bounded.arguments.items():
  13. # set the key and value in the instance of give class
  14. setattr(self, key, val)
  15. setattr(cls, '__init__', __init__)
  16. return cls
  17.  
  18. # the way you use it
  19. @r_dataclass
  20. class Vector:
  21. x: float
  22. y: float
  23.  
  24. @r_dataclass
  25. class Person:
  26. name: str
  27. age: int
  28.  
  29.  
  30.  
  31. if __name__ == '__main__':
  32. v = Vector(3.0, 4.3)
  33. print(v.x, v.y)
Add Comment
Please, Sign In to add comment