preinit.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. from typing import Any, Callable, Optional
  2. import wandb
  3. class PreInitObject:
  4. def __init__(self, name: str, destination: Optional[Any] = None) -> None:
  5. self._name = name
  6. if destination is not None:
  7. self.__doc__ = destination.__doc__
  8. def __getitem__(self, key: str) -> None:
  9. raise wandb.Error(f"You must call wandb.init() before {self._name}[{key!r}]")
  10. def __setitem__(self, key: str, value: Any) -> Any:
  11. raise wandb.Error(f"You must call wandb.init() before {self._name}[{key!r}]")
  12. def __setattr__(self, key: str, value: Any) -> Any:
  13. if not key.startswith("_"):
  14. raise wandb.Error(f"You must call wandb.init() before {self._name}.{key}")
  15. else:
  16. return object.__setattr__(self, key, value)
  17. def __getattr__(self, key: str) -> Any:
  18. if not key.startswith("_"):
  19. raise wandb.Error(f"You must call wandb.init() before {self._name}.{key}")
  20. else:
  21. raise AttributeError
  22. def PreInitCallable( # noqa: N802
  23. name: str, destination: Optional[Any] = None
  24. ) -> Callable:
  25. def preinit_wrapper(*args: Any, **kwargs: Any) -> Any:
  26. raise wandb.Error(f"You must call wandb.init() before {name}()")
  27. preinit_wrapper.__name__ = str(name)
  28. if destination:
  29. preinit_wrapper.__wrapped__ = destination # type: ignore
  30. preinit_wrapper.__doc__ = destination.__doc__
  31. return preinit_wrapper