當前位置: 首頁>>代碼示例>>Python>>正文


Python contextvars.ContextVar方法代碼示例

本文整理匯總了Python中contextvars.ContextVar方法的典型用法代碼示例。如果您正苦於以下問題:Python contextvars.ContextVar方法的具體用法?Python contextvars.ContextVar怎麽用?Python contextvars.ContextVar使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在contextvars的用法示例。


在下文中一共展示了contextvars.ContextVar方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _make_threadlocal_contextvars

# 需要導入模塊: import contextvars [as 別名]
# 或者: from contextvars import ContextVar [as 別名]
def _make_threadlocal_contextvars(local):
    # type: (type) -> type
    class ContextVar(object):
        # Super-limited impl of ContextVar

        def __init__(self, name):
            # type: (str) -> None
            self._name = name
            self._local = local()

        def get(self, default):
            # type: (Any) -> Any
            return getattr(self._local, "value", default)

        def set(self, value):
            # type: (Any) -> None
            self._local.value = value

    return ContextVar 
開發者ID:getsentry,項目名稱:sentry-python,代碼行數:21,代碼來源:utils.py

示例2: reset

# 需要導入模塊: import contextvars [as 別名]
# 或者: from contextvars import ContextVar [as 別名]
def reset(self, token):  # type: (Token) -> None
        if token.context_var is not self:
            raise ValueError('Token was created by a different ContextVar')
        if self._cv_variable is not None:
            if not isinstance(token, _ContextVarToken):
                raise TypeError('Unexpected `{}` expecting `_ContextVarToken`'.format(token.__class__.__name__))
            self._cv_variable.reset(token.token)
        elif self._tl_variable is not None:
            if not isinstance(token, _ThreadLocalToken):
                raise TypeError('Unexpected `{}` expecting `_ThreadLocalToken`'.format(token.__class__.__name__))
            if token.previous_value is _NO_DEFAULT:
                delattr(self._tl_variable, 'value')
            else:
                self._tl_variable.value = token.previous_value
        else:
            raise TypeError('This context var has been internally messed with and is no longer valid.') 
開發者ID:eventbrite,項目名稱:pysoa,代碼行數:18,代碼來源:compatibility.py

示例3: coroutine

# 需要導入模塊: import contextvars [as 別名]
# 或者: from contextvars import ContextVar [as 別名]
def coroutine(self, coroutine):
        create_call_trace.append('SpecialCoroutineMiddleware')

        # noinspection PyCompatibility
        async def wrapper():
            var = contextvars.ContextVar('middleware_var')  # type: contextvars.ContextVar[int]
            var.set(self.var_value)

            run_call_trace_pre.append('SpecialCoroutineMiddleware')

            try:
                return await coroutine
            finally:
                run_call_trace_post.append('SpecialCoroutineMiddleware')

        return wrapper() 
開發者ID:eventbrite,項目名稱:pysoa,代碼行數:18,代碼來源:test_event_loop.py

示例4: test_context_var_repr_1

# 需要導入模塊: import contextvars [as 別名]
# 或者: from contextvars import ContextVar [as 別名]
def test_context_var_repr_1(self):
        c = contextvars.ContextVar('a')
        self.assertIn('a', repr(c))

        c = contextvars.ContextVar('a', default=123)
        self.assertIn('123', repr(c))

        lst = []
        c = contextvars.ContextVar('a', default=lst)
        lst.append(c)
        self.assertIn('...', repr(c))
        self.assertIn('...', repr(lst))

        t = c.set(1)
        self.assertIn(repr(c), repr(t))
        self.assertNotIn(' used ', repr(t))
        c.reset(t)
        self.assertIn(' used ', repr(t)) 
開發者ID:bkerler,項目名稱:android_universal,代碼行數:20,代碼來源:test_context.py

示例5: test_context_getset_3

# 需要導入模塊: import contextvars [as 別名]
# 或者: from contextvars import ContextVar [as 別名]
def test_context_getset_3(self):
        c = contextvars.ContextVar('c', default=42)
        ctx = contextvars.Context()

        def fun():
            self.assertEqual(c.get(), 42)
            with self.assertRaises(KeyError):
                ctx[c]
            self.assertIsNone(ctx.get(c))
            self.assertEqual(ctx.get(c, 'spam'), 'spam')
            self.assertNotIn(c, ctx)
            self.assertEqual(list(ctx.keys()), [])

            t = c.set(1)
            self.assertEqual(list(ctx.keys()), [c])
            self.assertEqual(ctx[c], 1)

            c.reset(t)
            self.assertEqual(list(ctx.keys()), [])
            with self.assertRaises(KeyError):
                ctx[c]

        ctx.run(fun) 
開發者ID:bkerler,項目名稱:android_universal,代碼行數:25,代碼來源:test_context.py

示例6: test_context_copy_1

# 需要導入模塊: import contextvars [as 別名]
# 或者: from contextvars import ContextVar [as 別名]
def test_context_copy_1(self):
        ctx1 = contextvars.Context()
        c = contextvars.ContextVar('c', default=42)

        def ctx1_fun():
            c.set(10)

            ctx2 = ctx1.copy()
            self.assertEqual(ctx2[c], 10)

            c.set(20)
            self.assertEqual(ctx1[c], 20)
            self.assertEqual(ctx2[c], 10)

            ctx2.run(ctx2_fun)
            self.assertEqual(ctx1[c], 20)
            self.assertEqual(ctx2[c], 30)

        def ctx2_fun():
            self.assertEqual(c.get(), 10)
            c.set(30)
            self.assertEqual(c.get(), 30)

        ctx1.run(ctx1_fun) 
開發者ID:bkerler,項目名稱:android_universal,代碼行數:26,代碼來源:test_context.py

示例7: test_context_threads_1

# 需要導入模塊: import contextvars [as 別名]
# 或者: from contextvars import ContextVar [as 別名]
def test_context_threads_1(self):
        cvar = contextvars.ContextVar('cvar')

        def sub(num):
            for i in range(10):
                cvar.set(num + i)
                time.sleep(random.uniform(0.001, 0.05))
                self.assertEqual(cvar.get(), num + i)
            return num

        tp = concurrent.futures.ThreadPoolExecutor(max_workers=10)
        try:
            results = list(tp.map(sub, range(10)))
        finally:
            tp.shutdown()
        self.assertEqual(results, list(range(10)))


# HAMT Tests 
開發者ID:bkerler,項目名稱:android_universal,代碼行數:21,代碼來源:test_context.py

示例8: __init__

# 需要導入模塊: import contextvars [as 別名]
# 或者: from contextvars import ContextVar [as 別名]
def __init__(self, peer: Peer):
            self._cached_funcs = {}
            self.peer = peer
            self.order_key = ContextVar('order_key', default=None) 
開發者ID:lablup,項目名稱:backend.ai-manager,代碼行數:6,代碼來源:registry.py

示例9: test_contextvars

# 需要導入模塊: import contextvars [as 別名]
# 或者: from contextvars import ContextVar [as 別名]
def test_contextvars(self):
        from contextvars import ContextVar
        var = ContextVar('var')
        var.set(0)

        async def set_val():
            var.set(42)

        async def coro():
            await set_val()
            await asyncio.sleep(0.01)
            return var.get()

        result = self.loop.run_until_complete(coro())
        self.assertEqual(result, 42) 
開發者ID:erdewit,項目名稱:nest_asyncio,代碼行數:17,代碼來源:nest_test.py

示例10: _is_contextvars_broken

# 需要導入模塊: import contextvars [as 別名]
# 或者: from contextvars import ContextVar [as 別名]
def _is_contextvars_broken():
    # type: () -> bool
    """
    Returns whether gevent/eventlet have patched the stdlib in a way where thread locals are now more "correct" than contextvars.
    """
    try:
        from gevent.monkey import is_object_patched  # type: ignore

        if is_object_patched("threading", "local"):
            # Gevent 20.5 is able to patch both thread locals and contextvars,
            # in that case all is good.
            if is_object_patched("contextvars", "ContextVar"):
                return False

            return True
    except ImportError:
        pass

    try:
        from eventlet.patcher import is_monkey_patched  # type: ignore

        if is_monkey_patched("thread"):
            return True
    except ImportError:
        pass

    return False 
開發者ID:getsentry,項目名稱:sentry-python,代碼行數:29,代碼來源:utils.py

示例11: _get_contextvars

# 需要導入模塊: import contextvars [as 別名]
# 或者: from contextvars import ContextVar [as 別名]
def _get_contextvars():
    # type: () -> Tuple[bool, type]
    """
    Figure out the "right" contextvars installation to use. Returns a
    `contextvars.ContextVar`-like class with a limited API.

    See https://docs.sentry.io/platforms/python/contextvars/ for more information.
    """
    if not _is_contextvars_broken():
        # aiocontextvars is a PyPI package that ensures that the contextvars
        # backport (also a PyPI package) works with asyncio under Python 3.6
        #
        # Import it if available.
        if sys.version_info < (3, 7):
            # `aiocontextvars` is absolutely required for functional
            # contextvars on Python 3.6.
            try:
                from aiocontextvars import ContextVar  # noqa

                return True, ContextVar
            except ImportError:
                pass
        else:
            # On Python 3.7 contextvars are functional.
            try:
                from contextvars import ContextVar

                return True, ContextVar
            except ImportError:
                pass

    # Fall back to basic thread-local usage.

    from threading import local

    return False, _make_threadlocal_contextvars(local) 
開發者ID:getsentry,項目名稱:sentry-python,代碼行數:38,代碼來源:utils.py

示例12: __init__

# 需要導入模塊: import contextvars [as 別名]
# 或者: from contextvars import ContextVar [as 別名]
def __init__(self, name):
        """Initialize a StackVar."""
        self.var = ContextVar(name, default=(None, None))
        self.var.set((None, None)) 
開發者ID:mila-iqia,項目名稱:myia,代碼行數:6,代碼來源:info.py

示例13: __init__

# 需要導入模塊: import contextvars [as 別名]
# 或者: from contextvars import ContextVar [as 別名]
def __init__(self) -> None:
        self._current_context = ContextVar(
            self._CONTEXT_KEY, default=Context()
        ) 
開發者ID:open-telemetry,項目名稱:opentelemetry-python,代碼行數:6,代碼來源:contextvars_context.py

示例14: __init_subclass__

# 需要導入模塊: import contextvars [as 別名]
# 或者: from contextvars import ContextVar [as 別名]
def __init_subclass__(cls, **kwargs):
        cls.__context_instance = contextvars.ContextVar(
            "instance_" + (kwargs.get("ctx_name") or cls.__name__)
        )
        return cls 
開發者ID:timoniq,項目名稱:vkbottle,代碼行數:7,代碼來源:util.py

示例15: __init__

# 需要導入模塊: import contextvars [as 別名]
# 或者: from contextvars import ContextVar [as 別名]
def __init__(self, name, default):
            self.name = name
            self.contextvar = contextvars.ContextVar(name)
            self.default = default if callable(default) else (lambda: default) 
開發者ID:census-instrumentation,項目名稱:opencensus-python,代碼行數:6,代碼來源:__init__.py


注:本文中的contextvars.ContextVar方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。