_compat.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import sys
  2. import platform
  3. __all__ = ['install', 'NullFinder']
  4. def install(flag):
  5. def dec_install(cls):
  6. """
  7. Class decorator for installation on sys.meta_path.
  8. Adds the backport DistributionFinder to sys.meta_path and
  9. attempts to disable the finder functionality of the stdlib
  10. DistributionFinder.
  11. """
  12. if flag:
  13. sys.meta_path.append(cls())
  14. disable_stdlib_finder()
  15. return cls
  16. return dec_install
  17. def disable_stdlib_finder():
  18. """
  19. Give the backport primacy for discovering path-based distributions
  20. by monkey-patching the stdlib O_O.
  21. See #91 for more background for rationale on this sketchy
  22. behavior.
  23. """
  24. def matches(finder):
  25. return getattr(
  26. finder, '__module__', None
  27. ) == '_frozen_importlib_external' and hasattr(finder, 'find_distributions')
  28. for finder in filter(matches, sys.meta_path): # pragma: nocover
  29. del finder.find_distributions
  30. class NullFinder:
  31. """
  32. A "Finder" (aka "MetaPathFinder") that never finds any modules,
  33. but may find distributions.
  34. """
  35. @staticmethod
  36. def find_spec(*args, **kwargs):
  37. return None
  38. def pypy_partial(val):
  39. """
  40. Adjust for variable stacklevel on partial under PyPy.
  41. Workaround for #327.
  42. """
  43. is_pypy = platform.python_implementation() == 'PyPy'
  44. return val + is_pypy