_compat.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. ##############################################################################
  2. #
  3. # Copyright (c) 2006 Zope Foundation and Contributors.
  4. # All Rights Reserved.
  5. #
  6. # This software is subject to the provisions of the Zope Public License,
  7. # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
  8. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
  9. # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  10. # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
  11. # FOR A PARTICULAR PURPOSE.
  12. #
  13. ##############################################################################
  14. """
  15. Support functions for dealing with differences in platforms, including Python
  16. versions and implementations.
  17. This file should have no imports from the rest of zope.interface because it is
  18. used during early bootstrapping.
  19. """
  20. import os
  21. import sys
  22. import types
  23. if sys.version_info[0] < 3:
  24. def _normalize_name(name):
  25. if isinstance(name, basestring):
  26. return unicode(name)
  27. raise TypeError("name must be a regular or unicode string")
  28. CLASS_TYPES = (type, types.ClassType)
  29. STRING_TYPES = (basestring,)
  30. _BUILTINS = '__builtin__'
  31. PYTHON3 = False
  32. PYTHON2 = True
  33. else:
  34. def _normalize_name(name):
  35. if isinstance(name, bytes):
  36. name = str(name, 'ascii')
  37. if isinstance(name, str):
  38. return name
  39. raise TypeError("name must be a string or ASCII-only bytes")
  40. CLASS_TYPES = (type,)
  41. STRING_TYPES = (str,)
  42. _BUILTINS = 'builtins'
  43. PYTHON3 = True
  44. PYTHON2 = False
  45. PYPY = hasattr(sys, 'pypy_version_info')
  46. PYPY2 = PYTHON2 and PYPY
  47. def _skip_under_py3k(test_method):
  48. import unittest
  49. return unittest.skipIf(sys.version_info[0] >= 3, "Only on Python 2")(test_method)
  50. def _skip_under_py2(test_method):
  51. import unittest
  52. return unittest.skipIf(sys.version_info[0] < 3, "Only on Python 3")(test_method)
  53. def _c_optimizations_required():
  54. """
  55. Return a true value if the C optimizations are required.
  56. This uses the ``PURE_PYTHON`` variable as documented in `_use_c_impl`.
  57. """
  58. pure_env = os.environ.get('PURE_PYTHON')
  59. require_c = pure_env == "0"
  60. return require_c
  61. def _c_optimizations_available():
  62. """
  63. Return the C optimization module, if available, otherwise
  64. a false value.
  65. If the optimizations are required but not available, this
  66. raises the ImportError.
  67. This does not say whether they should be used or not.
  68. """
  69. catch = () if _c_optimizations_required() else (ImportError,)
  70. try:
  71. from zope.interface import _zope_interface_coptimizations as c_opt
  72. return c_opt
  73. except catch: # pragma: no cover (only Jython doesn't build extensions)
  74. return False
  75. def _c_optimizations_ignored():
  76. """
  77. The opposite of `_c_optimizations_required`.
  78. """
  79. pure_env = os.environ.get('PURE_PYTHON')
  80. return pure_env is not None and pure_env != "0"
  81. def _should_attempt_c_optimizations():
  82. """
  83. Return a true value if we should attempt to use the C optimizations.
  84. This takes into account whether we're on PyPy and the value of the
  85. ``PURE_PYTHON`` environment variable, as defined in `_use_c_impl`.
  86. """
  87. is_pypy = hasattr(sys, 'pypy_version_info')
  88. if _c_optimizations_required():
  89. return True
  90. if is_pypy:
  91. return False
  92. return not _c_optimizations_ignored()
  93. def _use_c_impl(py_impl, name=None, globs=None):
  94. """
  95. Decorator. Given an object implemented in Python, with a name like
  96. ``Foo``, import the corresponding C implementation from
  97. ``zope.interface._zope_interface_coptimizations`` with the name
  98. ``Foo`` and use it instead.
  99. If the ``PURE_PYTHON`` environment variable is set to any value
  100. other than ``"0"``, or we're on PyPy, ignore the C implementation
  101. and return the Python version. If the C implementation cannot be
  102. imported, return the Python version. If ``PURE_PYTHON`` is set to
  103. 0, *require* the C implementation (let the ImportError propagate);
  104. note that PyPy can import the C implementation in this case (and all
  105. tests pass).
  106. In all cases, the Python version is kept available. in the module
  107. globals with the name ``FooPy`` and the name ``FooFallback`` (both
  108. conventions have been used; the C implementation of some functions
  109. looks for the ``Fallback`` version, as do some of the Sphinx
  110. documents).
  111. Example::
  112. @_use_c_impl
  113. class Foo(object):
  114. ...
  115. """
  116. name = name or py_impl.__name__
  117. globs = globs or sys._getframe(1).f_globals
  118. def find_impl():
  119. if not _should_attempt_c_optimizations():
  120. return py_impl
  121. c_opt = _c_optimizations_available()
  122. if not c_opt: # pragma: no cover (only Jython doesn't build extensions)
  123. return py_impl
  124. __traceback_info__ = c_opt
  125. return getattr(c_opt, name)
  126. c_impl = find_impl()
  127. # Always make available by the FooPy name and FooFallback
  128. # name (for testing and documentation)
  129. globs[name + 'Py'] = py_impl
  130. globs[name + 'Fallback'] = py_impl
  131. return c_impl