Skip to content

Instantly share code, notes, and snippets.

@mypy-play
Created August 30, 2026 11:56
Show Gist options
  • Select an option

  • Save mypy-play/85659e21b5a27d923a2dcaa2d5d65563 to your computer and use it in GitHub Desktop.

Select an option

Save mypy-play/85659e21b5a27d923a2dcaa2d5d65563 to your computer and use it in GitHub Desktop.
Shared via mypy Playground
from __future__ import annotations
from dataclasses import dataclass
from contextvars import ContextVar, copy_context
from typing import Generic, TypeVar, overload, reveal_type
T = TypeVar("T")
class CtxProperty(Generic[T]):
var: ContextVar[T]
def __init__(self, var: ContextVar[T]) -> None:
reveal_type(var)
self.var = var
def __set_name__(self, owner, name):
reveal_type(owner)
reveal_type(name)
assert name == self.var.name
@overload
def __get__(self, instance: None, owner) -> CtxProperty[T]: ...
@overload
def __get__(self, instance, owner) -> T: ...
def __get__(self, instance, owner=None) -> T | CtxProperty[T]:
print(f"get: {type(instance)=}, {owner=}, var={self.var}")
if instance is None:
return self
return self.var.get()
def __set__(self, instance, value: T) -> None:
print(f"set: {type(instance)=}, var={self.var}, {value=}")
self.var.set(value)
@dataclass
class _Context:
foo: CtxProperty[int] = CtxProperty(ContextVar("foo"))
bar: CtxProperty[str] = CtxProperty(ContextVar("bar"))
ctx = _Context(
foo = 0,
bar = "hello",
)
reveal_type(ctx.foo)
reveal_type(ctx.bar)
print(ctx)
print(dict(copy_context()))
ctx.foo = 42
ctx.bar = "hello"
print(ctx)
print(dict(copy_context()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment