typing.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. """For neatly implementing static typing in pip.
  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 pip, all static-typing related imports should be guarded as follows:
  15. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  16. if MYPY_CHECK_RUNNING:
  17. from typing import ...
  18. Ref: https://github.com/python/mypy/issues/3216
  19. """
  20. MYPY_CHECK_RUNNING = False
  21. if MYPY_CHECK_RUNNING:
  22. from typing import cast
  23. else:
  24. # typing's cast() is needed at runtime, but we don't want to import typing.
  25. # Thus, we use a dummy no-op version, which we tell mypy to ignore.
  26. def cast(type_, value): # type: ignore
  27. return value