_pep562.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. """
  2. Backport of PEP 562.
  3. https://pypi.org/search/?q=pep562
  4. Licensed under MIT
  5. Copyright (c) 2018 Isaac Muse <isaacmuse@gmail.com>
  6. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
  7. documentation files (the "Software"), to deal in the Software without restriction, including without limitation
  8. the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
  9. and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all copies or substantial portions
  11. of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  13. TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  14. THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  15. CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  16. IN THE SOFTWARE.
  17. """
  18. import sys
  19. from typing import Any, Callable, List, Optional
  20. class Pep562:
  21. """
  22. Backport of PEP 562 <https://pypi.org/search/?q=pep562>.
  23. Wraps the module in a class that exposes the mechanics to override `__dir__` and `__getattr__`.
  24. The given module will be searched for overrides of `__dir__` and `__getattr__` and use them when needed.
  25. """
  26. def __init__(self, name: str) -> None:
  27. """Acquire `__getattr__` and `__dir__`, but only replace module for versions less than Python 3.7."""
  28. self._module = sys.modules[name]
  29. self._get_attr = getattr(self._module, "__getattr__", None)
  30. self._get_dir: Optional[Callable[..., List[str]]] = getattr(
  31. self._module, "__dir__", None
  32. )
  33. sys.modules[name] = self # type: ignore[assignment]
  34. def __dir__(self) -> List[str]:
  35. """Return the overridden `dir` if one was provided, else apply `dir` to the module."""
  36. return self._get_dir() if self._get_dir else dir(self._module)
  37. def __getattr__(self, name: str) -> Any:
  38. """
  39. Attempt to retrieve the attribute from the module, and if missing, use the overridden function if present.
  40. """
  41. try:
  42. return getattr(self._module, name)
  43. except AttributeError:
  44. if self._get_attr:
  45. return self._get_attr(name)
  46. raise
  47. def pep562(module_name: str) -> None:
  48. """Helper function to apply PEP 562."""
  49. if sys.version_info < (3, 7):
  50. Pep562(module_name)