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 15def _contextvars_supported(): 16 """Determines if the contextvars module is supported. 17 18 We use a 'try it and see if it works approach' here rather than predicting 19 based on interpreter version in order to support older interpreters that 20 may have a backported module based on, e.g. `threading.local`. 21 22 Returns: 23 A bool indicating whether `contextvars` are supported in the current 24 environment. 25 """ 26 try: 27 import contextvars 28 return True 29 except ImportError: 30 return False 31 32 33def _run_with_context(target): 34 """Runs a callable with contextvars propagated. 35 36 If contextvars are supported, the calling thread's context will be copied 37 and propagated. If they are not supported, this function is equivalent 38 to the identity function. 39 40 Args: 41 target: A callable object to wrap. 42 Returns: 43 A callable object with the same signature as `target` but with 44 contextvars propagated. 45 """ 46 47 48if _contextvars_supported(): 49 import contextvars 50 def _run_with_context(target): 51 ctx = contextvars.copy_context() 52 def _run(*args): 53 ctx.run(target, *args) 54 return _run 55else: 56 def _run_with_context(target): 57 def _run(*args): 58 target(*args) 59 return _run 60