thread.pyx.pxi 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # Copyright 2020 The gRPC authors.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. def _contextvars_supported():
  15. """Determines if the contextvars module is supported.
  16. We use a 'try it and see if it works approach' here rather than predicting
  17. based on interpreter version in order to support older interpreters that
  18. may have a backported module based on, e.g. `threading.local`.
  19. Returns:
  20. A bool indicating whether `contextvars` are supported in the current
  21. environment.
  22. """
  23. try:
  24. import contextvars
  25. return True
  26. except ImportError:
  27. return False
  28. def _run_with_context(target):
  29. """Runs a callable with contextvars propagated.
  30. If contextvars are supported, the calling thread's context will be copied
  31. and propagated. If they are not supported, this function is equivalent
  32. to the identity function.
  33. Args:
  34. target: A callable object to wrap.
  35. Returns:
  36. A callable object with the same signature as `target` but with
  37. contextvars propagated.
  38. """
  39. if _contextvars_supported():
  40. import contextvars
  41. def _run_with_context(target):
  42. ctx = contextvars.copy_context()
  43. def _run(*args):
  44. ctx.run(target, *args)
  45. return _run
  46. else:
  47. def _run_with_context(target):
  48. def _run(*args):
  49. target(*args)
  50. return _run