attach_tools.py 619 B

1234567891011121314151617181920
  1. class Attach(object):
  2. def __init__(self, dst):
  3. self.dst = dst
  4. def __call__(self, obj, name=None):
  5. if name is None:
  6. # Automatically get names of functions and classes
  7. name = obj.__name__
  8. if hasattr(self.dst, name):
  9. raise RuntimeError(
  10. f"{self.dst} already has the attribute {name}, which is {getattr(self.dst, name)}."
  11. )
  12. setattr(self.dst, name, obj)
  13. if hasattr(self.dst, '__all__'):
  14. self.dst.__all__.append(name)
  15. return obj
  16. @staticmethod
  17. def to(dst):
  18. return Attach(dst)