argument.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import pyaml
  2. from dataclasses import dataclass
  3. class Argument(object):
  4. def __init__(self, *args, **kw):
  5. super(Argument, self).__init__()
  6. self.args = args # positional arugments
  7. self.kw = kw # keyword arguments
  8. class FileArgument(Argument):
  9. def __init__(self, *args, **kw):
  10. super(FileArgument, self).__init__(*args, **kw)
  11. @classmethod
  12. def mode(cls, file_mode, encoding=None):
  13. def wrapper(*args, **kw):
  14. obj = cls(*args, **kw)
  15. obj.kw["type"] = argparse.FileType(file_mode, encoding=encoding)
  16. return obj
  17. return wrapper
  18. def JupyterArguments(cls=None, *args, repr=False, **kwargs):
  19. def _yaml_repr_(self) -> str:
  20. cls_name = type(self).__name__
  21. return pyaml.dump({cls_name: self.__dict__}, sort_dicts=False)
  22. def wrap(cls):
  23. if not repr and "__repr__" not in cls.__dict__:
  24. setattr(cls, "__repr__", _yaml_repr_)
  25. return dataclass(cls, *args, repr=repr, **kwargs)
  26. # See if we're being called as @dataclass or @dataclass().
  27. if cls is None:
  28. return wrap
  29. return wrap(cls)
  30. if __name__ == '__main__':
  31. @JupyterArguments
  32. class Args:
  33. arg1: int = 0
  34. arg2: int = 1
  35. print(Args())