https://github.com/wyfo/contextclass
Easy typed interface for ContextVar
https://github.com/wyfo/contextclass
Last synced: 7 months ago
JSON representation
Easy typed interface for ContextVar
- Host: GitHub
- URL: https://github.com/wyfo/contextclass
- Owner: wyfo
- License: mit
- Created: 2019-10-19T16:19:55.000Z (almost 6 years ago)
- Default Branch: master
- Last Pushed: 2020-01-09T17:26:22.000Z (over 5 years ago)
- Last Synced: 2025-01-11T16:13:27.695Z (9 months ago)
- Language: Python
- Size: 9.77 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# contextclasses - Context classes
Context classes provide a typed interface over a [context variable](https://docs.python.org/3/library/contextvars.html#contextvars.ContextVar) dictionary.
It can be used for example to reproduce Flask (thread-local) ["global" context](https://flask.palletsprojects.com/en/1.1.x/appcontext/) in an async web framework.# Example
```python
import asyncio
from contextclasses import contextclassasync def test_use_case():
@contextclass
class Ctx:
n: intasync def use_ctx(n: int):
Ctx.n = n
await asyncio.sleep(0) # switch context
return Ctx.nvalues = [*range(5)]
result = await asyncio.gather(*(use_ctx(n) for n in values))
assert result == values
```For more examples, please look at the [tests](tests)