contextmodel 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,147 @@
1
+ from collections.abc import Callable, Generator
2
+ from contextlib import contextmanager
3
+ from contextvars import ContextVar, Token
4
+ from functools import cache, partial
5
+ from typing import ClassVar
6
+
7
+
8
+ class Context[M: ContextModel, **P]:
9
+ """
10
+ Context. Call it to create a new object.
11
+
12
+ >>> from dataclasses import dataclass
13
+
14
+ >>> @dataclass
15
+ ... class Foo(ContextModel):
16
+ ... x: int | None = None
17
+
18
+ >>> @context_create(Foo, x=1)
19
+ ... def f() -> None:
20
+ ... print(context_get(Foo))
21
+ >>> f()
22
+ Foo(x=1)
23
+
24
+ >>> with Foo.model_context.create(x=2):
25
+ ... print(Foo.model_current.x)
26
+ 2
27
+
28
+ >>> @Foo.model_context.create(x=3)
29
+ ... def f() -> None:
30
+ ... print(Foo.model_current.x)
31
+ >>> f()
32
+ 3
33
+
34
+ """
35
+
36
+ def __init__(self, model_class: Callable[P, M], variable: ContextVar[M]) -> None:
37
+ self.model_class = model_class
38
+ self.variable = variable
39
+
40
+ def get(self) -> M:
41
+ return self.variable.get()
42
+
43
+ def set(self, model: M) -> Generator[Token[M]]:
44
+ token = self.variable.set(model)
45
+ try:
46
+ yield token
47
+ finally:
48
+ token.var.reset(token)
49
+
50
+ @contextmanager
51
+ def create(self, *args: P.args, **kwargs: P.kwargs) -> Generator[Token[M]]:
52
+ return self.set(self.model_class(*args, **kwargs))
53
+
54
+
55
+ def context_get[M: ContextModel](model_class: type[M]) -> M:
56
+ """
57
+ Get the current context model instance.
58
+
59
+ >>> from dataclasses import dataclass, field
60
+
61
+ >>> @dataclass
62
+ ... class Foo(ContextModel):
63
+ ... x: int = 1
64
+
65
+ >>> with Foo.model_context.create(x=2):
66
+ ... print(context_get(Foo))
67
+ Foo(x=2)
68
+ """
69
+ return context_of(model_class).get()
70
+
71
+
72
+ def future_context_get[M: ContextModel](model_class: type[M]) -> Callable[[], M]:
73
+ """
74
+ Return a callback to return a value from context. Useful as "factories".
75
+
76
+ >>> from dataclasses import dataclass, field
77
+
78
+ >>> @dataclass
79
+ ... class Foo(ContextModel):
80
+ ... x: int = 1
81
+
82
+ >>> @dataclass
83
+ ... class MyData:
84
+ ... foo: Foo = field(default_factory=future_context_get(Foo))
85
+
86
+ >>> MyData(foo=Foo())
87
+ MyData(foo=Foo(x=1))
88
+
89
+ >>> with Foo.model_context.create(x=2):
90
+ ... print(MyData())
91
+ MyData(foo=Foo(x=2))
92
+
93
+ """
94
+ return partial(context_get, model_class)
95
+
96
+
97
+ @cache
98
+ def context_of[M: ContextModel, **P](
99
+ model_class: Callable[P, M],
100
+ ) -> Context[M, P]:
101
+ auto_name = getattr(model_class, "__name__", format(model_class))
102
+ return Context(model_class=model_class, variable=ContextVar[M](auto_name))
103
+
104
+
105
+ @contextmanager
106
+ def context_create[**P, M: Context](
107
+ model_class: Callable[P, M],
108
+ /,
109
+ *args: P.args,
110
+ **kwargs: P.kwargs,
111
+ ) -> Generator[M]:
112
+ context = context_of(model_class)
113
+ return context.set(context.model_class(*args, **kwargs))
114
+
115
+
116
+ @contextmanager
117
+ def context_set[**P, M: Context](
118
+ model_class: Callable[P, M],
119
+ /,
120
+ *args: P.args,
121
+ **kwargs: P.kwargs,
122
+ ) -> Generator[M]:
123
+ context = context_of(model_class)
124
+ return context.set(context.model_class(*args, **kwargs))
125
+
126
+
127
+ class _ContextGetter:
128
+ def __get__[M: ContextModel, **P](
129
+ self,
130
+ instance: M | None,
131
+ owner: Callable[P, M],
132
+ ) -> Context[M, P]:
133
+ return context_of(owner or type(instance))
134
+
135
+
136
+ class _ModelGetter:
137
+ def __get__[M: ContextModel, **P](
138
+ self,
139
+ instance: M | None,
140
+ owner: Callable[P, M],
141
+ ) -> M:
142
+ return context_get(owner if instance is None else instance) # type: ignore[invalid-argument-type]
143
+
144
+
145
+ class ContextModel:
146
+ model_context: ClassVar[_ContextGetter] = _ContextGetter()
147
+ model_current: ClassVar[_ModelGetter] = _ModelGetter()
contextmodel/py.typed ADDED
File without changes
@@ -0,0 +1,41 @@
1
+ Metadata-Version: 2.4
2
+ Name: contextmodel
3
+ Version: 0.1.0
4
+ Summary: A nice interface to context variables
5
+ License-File: LICENSE
6
+ Requires-Python: >=3.12
7
+ Description-Content-Type: text/markdown
8
+
9
+ # contextmodel
10
+ Alternative interface to context variables for practical scenarios.
11
+
12
+ ```pycon
13
+ >>> from contextmodel import ContextModel, context_create, context_get
14
+ >>> from dataclasses import dataclass
15
+
16
+ >>> @dataclass
17
+ ... class Foo(ContextModel):
18
+ ... x: int | None = None
19
+
20
+ >>> @context_create(Foo, x=1)
21
+ ... def f() -> None:
22
+ ... print(context_get(Foo))
23
+ >>> f()
24
+ Foo(x=1)
25
+
26
+ >>> with Foo.model_context.create(x=2):
27
+ ... print(Foo.model_current.x)
28
+ 2
29
+
30
+ >>> @Foo.model_context.create(x=3)
31
+ ... def f() -> None:
32
+ ... print(Foo.model_current.x)
33
+ >>> f()
34
+ 3
35
+
36
+
37
+ ```
38
+
39
+ Works with type hints:
40
+
41
+ <img width="821" height="454" alt="image" src="https://github.com/user-attachments/assets/6c4f5b4b-48b5-4807-a6aa-bf9cd6b8e3e4" />
@@ -0,0 +1,6 @@
1
+ contextmodel/__init__.py,sha256=frW0xGdXry1O3B2sT-II9yh_ZAPUTKh_tbFpkJqKNLE,3679
2
+ contextmodel/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ contextmodel-0.1.0.dist-info/METADATA,sha256=W4x_m6qETawpngRKWkYi7zINIF3x5JtCma7XzUaGHpU,909
4
+ contextmodel-0.1.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
5
+ contextmodel-0.1.0.dist-info/licenses/LICENSE,sha256=9iNQ2_-JNctKZJ2HyRpDx6JOHpRKSE_nGmZUEaCcbKE,1074
6
+ contextmodel-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.28.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bartosz Sławecki
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.