You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1.8KB

  1. """For neatly implementing static typing in packaging.
  2. `mypy` - the static type analysis tool we use - uses the `typing` module, which
  3. provides core functionality fundamental to mypy's functioning.
  4. Generally, `typing` would be imported at runtime and used in that fashion -
  5. it acts as a no-op at runtime and does not have any run-time overhead by
  6. design.
  7. As it turns out, `typing` is not vendorable - it uses separate sources for
  8. Python 2/Python 3. Thus, this codebase can not expect it to be present.
  9. To work around this, mypy allows the typing import to be behind a False-y
  10. optional to prevent it from running at runtime and type-comments can be used
  11. to remove the need for the types to be accessible directly during runtime.
  12. This module provides the False-y guard in a nicely named fashion so that a
  13. curious maintainer can reach here to read this.
  14. In packaging, all static-typing related imports should be guarded as follows:
  15. from packaging._typing import TYPE_CHECKING
  16. if TYPE_CHECKING:
  17. from typing import ...
  18. Ref: https://github.com/python/mypy/issues/3216
  19. """
  20. __all__ = ["TYPE_CHECKING", "cast"]
  21. # The TYPE_CHECKING constant defined by the typing module is False at runtime
  22. # but True while type checking.
  23. if False: # pragma: no cover
  24. from typing import TYPE_CHECKING
  25. else:
  26. TYPE_CHECKING = False
  27. # typing's cast syntax requires calling typing.cast at runtime, but we don't
  28. # want to import typing at runtime. Here, we inform the type checkers that
  29. # we're importing `typing.cast` as `cast` and re-implement typing.cast's
  30. # runtime behavior in a block that is ignored by type checkers.
  31. if TYPE_CHECKING: # pragma: no cover
  32. # not executed at runtime
  33. from typing import cast
  34. else:
  35. # executed at runtime
  36. def cast(type_, value): # noqa
  37. return value