contextmodel 0.1.0__tar.gz

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,128 @@
1
+ name: ci
2
+
3
+ on:
4
+ push:
5
+ branches: ['main', 'test-me-*']
6
+ tags: ['v*']
7
+ pull_request:
8
+
9
+ concurrency:
10
+ group: ${{ github.workflow }}-${{ github.ref }}
11
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
12
+
13
+ env:
14
+ UV_LOCKED: 1
15
+ UV_NO_SYNC: 1
16
+
17
+ defaults:
18
+ run:
19
+ shell: bash
20
+
21
+ jobs:
22
+ check:
23
+ if: ${{ !cancelled() }}
24
+ name: ${{ matrix.version }} ${{matrix.platform}}
25
+ runs-on: ${{ matrix.platform }}
26
+
27
+ env:
28
+ FORCE_COLOR: 1
29
+ PY_COLORS: 1
30
+ UV_PYTHON: ${{ matrix.version }}
31
+
32
+ strategy:
33
+ fail-fast: false
34
+ # https://blog.jaraco.com/efficient-use-of-ci-resources/
35
+ matrix:
36
+ version: ['3.12', '3.14']
37
+ platform: [ubuntu-latest, windows-latest]
38
+ include:
39
+ - version: '3.13'
40
+ platform: ubuntu-latest
41
+
42
+ steps:
43
+ - uses: actions/checkout@v4
44
+ with:
45
+ submodules: true
46
+
47
+ - uses: astral-sh/setup-uv@v6
48
+ with:
49
+ enable-cache: true
50
+
51
+ - name: Install
52
+ id: install
53
+ run: uv sync
54
+
55
+ - name: Run unit tests
56
+ run: uv run pytest -vv
57
+ if: ${{ !cancelled() && steps.install.conclusion == 'success' }}
58
+
59
+ - name: Check formatting
60
+ id: formatting
61
+ run: uv run ruff format . --diff
62
+ if: ${{ !cancelled() && steps.install.conclusion == 'success' }}
63
+
64
+ - name: Lint
65
+ id: linting
66
+ run: uv run ruff check --output-format github
67
+ if: ${{ !cancelled() && steps.install.conclusion == 'success' }}
68
+
69
+ - name: Check type safety
70
+ id: types
71
+ run: uv run ty check .
72
+ if: ${{ !cancelled() && steps.install.conclusion == 'success' }}
73
+
74
+ release:
75
+ needs: [check]
76
+
77
+ if: ${{ github.ref_type == 'tag' }}
78
+
79
+ name: pypi release
80
+ runs-on: ubuntu-latest
81
+ environment: release
82
+
83
+ permissions:
84
+ id-token: write
85
+ contents: write
86
+ pull-requests: write
87
+
88
+ steps:
89
+ - uses: actions/checkout@v4
90
+ with:
91
+ fetch-depth: 0
92
+ submodules: true
93
+ persist-credentials: false
94
+
95
+ - uses: astral-sh/setup-uv@v6
96
+ with:
97
+ enable-cache: true
98
+
99
+ - name: Validate tag
100
+ id: validate-tag
101
+ run: |
102
+ set -CETeuxo pipefail
103
+
104
+ project_version=v$(uvx --with hatch-vcs hatchling version)
105
+ tag=${GITHUB_REF#refs/tags/}
106
+
107
+ [[ "$tag" == "$project_version" ]] || {
108
+ echo "Tag $tag does not match project version $project_version."
109
+ echo "Did you properly bump the version / set up dynamic versioning?"
110
+ exit 1
111
+ }
112
+
113
+ - name: Build package distributions
114
+ id: build
115
+ run: uv build --out-dir dist
116
+
117
+ - name: Publish package distributions
118
+ uses: pypa/gh-action-pypi-publish@release/v1
119
+
120
+ - name: 'Create a GitHub release'
121
+ uses: ncipollo/release-action@v1.18.0
122
+ with:
123
+ prerelease: false
124
+ draft: false
125
+ makeLatest: true
126
+ tag: "${{ github.ref_name }}"
127
+ name: "${{ github.ref_name }}"
128
+ generateReleaseNotes: true
@@ -0,0 +1,21 @@
1
+ # See https://pre-commit.com for more information
2
+ default_install_hook_types: [pre-commit, pre-push]
3
+ repos:
4
+ - repo: https://github.com/pre-commit/pre-commit-hooks
5
+ rev: v5.0.0
6
+ hooks:
7
+ - id: trailing-whitespace
8
+ - id: end-of-file-fixer
9
+ - id: check-yaml
10
+ - id: debug-statements
11
+ - repo: https://github.com/astral-sh/ruff-pre-commit
12
+ rev: v0.12.5
13
+ hooks:
14
+ - id: ruff-check
15
+ args: [--fix]
16
+ - id: ruff-format
17
+ - repo: https://github.com/astral-sh/uv-pre-commit
18
+ rev: 0.9.26
19
+ hooks:
20
+ - id: uv-lock
21
+ stages: [pre-push]
@@ -0,0 +1 @@
1
+ 3.12
@@ -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.
@@ -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,33 @@
1
+ # contextmodel
2
+ Alternative interface to context variables for practical scenarios.
3
+
4
+ ```pycon
5
+ >>> from contextmodel import ContextModel, context_create, context_get
6
+ >>> from dataclasses import dataclass
7
+
8
+ >>> @dataclass
9
+ ... class Foo(ContextModel):
10
+ ... x: int | None = None
11
+
12
+ >>> @context_create(Foo, x=1)
13
+ ... def f() -> None:
14
+ ... print(context_get(Foo))
15
+ >>> f()
16
+ Foo(x=1)
17
+
18
+ >>> with Foo.model_context.create(x=2):
19
+ ... print(Foo.model_current.x)
20
+ 2
21
+
22
+ >>> @Foo.model_context.create(x=3)
23
+ ... def f() -> None:
24
+ ... print(Foo.model_current.x)
25
+ >>> f()
26
+ 3
27
+
28
+
29
+ ```
30
+
31
+ Works with type hints:
32
+
33
+ <img width="821" height="454" alt="image" src="https://github.com/user-attachments/assets/6c4f5b4b-48b5-4807-a6aa-bf9cd6b8e3e4" />
@@ -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()
File without changes
@@ -0,0 +1,121 @@
1
+ [build-system]
2
+ requires = ["hatchling", "hatch-vcs"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "contextmodel"
7
+ dynamic = ["version"]
8
+ description = "A nice interface to context variables"
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+ dependencies = []
12
+
13
+ [dependency-groups]
14
+ dev = ["pre-commit>=4.2.0", "ruff>=0.11.8", "ty>=0.0.13"]
15
+ test = [
16
+ "detect-test-pollution>=1.2.0",
17
+ "hypothesis>=6.131.0",
18
+ "inline-snapshot>=0.20.8",
19
+ "pytest>=8.3.4",
20
+ "pytest-accept>=0.1.12",
21
+ "pytest-mock>=3.14.0",
22
+ "pytest-subtests>=0.14.1",
23
+ "pytest-sugar>=1.0.0",
24
+ ]
25
+ types = []
26
+ docs = [
27
+ "markdown-exec>=1.10.3",
28
+ "mike>=2.1.3",
29
+ "mkdocs>=1.6.1",
30
+ "mkdocs-git-revision-date-localized-plugin>=1.4.5",
31
+ "mkdocs-macros-plugin>=1.3.7",
32
+ "mkdocs-material>=9.6.13",
33
+ "mkdocstrings>=0.29.1",
34
+ "mkdocstrings-python>=1.16.10",
35
+ ]
36
+
37
+ [tool.uv]
38
+ required-version = "~=0.9"
39
+ default-groups = ["dev", "test", "types", "docs"]
40
+
41
+ [tool.hatch.version]
42
+ source = "vcs"
43
+
44
+ [tool.pytest.ini_options]
45
+ pythonpath = "."
46
+ addopts = ["--import-mode=importlib", "--doctest-modules", "--doctest-glob=**.md"]
47
+
48
+ [tool.ruff.lint]
49
+ exclude = ["**samples/**"]
50
+ select = ["ALL"]
51
+ ignore = [
52
+ # Description: Dynamically typed expressions (typing.Any) are disallowed
53
+ # Rationale:
54
+ # We use Any to allow user to constrain return types of our functions on their own.
55
+ # For example, having a function `def foo() -> Any: ...` allows user to write
56
+ # `my_foo: int = foo()` and have it passed type checking, since `Any` as a gradual
57
+ # form is assignable to any type
58
+ "ANN401",
59
+
60
+ # Description: 1 blank line required before class docstring
61
+ # Rationale: Remove the warning -- D211 (no-blank-line-before-class) preferred
62
+ "D203",
63
+
64
+ # Description: Multi-line docstring summary should start at the second line
65
+ # Rationale: Remove the warning -- D213 (multi-line-summary-second-line) preferred
66
+ "D212",
67
+
68
+ # Description: Line contains TODO, consider resolving the issue
69
+ # Rationale: Not appropriate for the project
70
+ "FIX002",
71
+
72
+ # Description: Implicitly concatenated string literals on one line
73
+ # Rationale: Conflicts with the formatter
74
+ "ISC001",
75
+
76
+ # Description: Function is too complex
77
+ # Rationale: Marginal importance
78
+ "C901",
79
+
80
+ # Description: Trailing comma missing
81
+ # Rationale: Conflicts with the formatter
82
+ "COM812",
83
+
84
+ # Description: File is part of an implicit namespace package. Add an `__init__.py`
85
+ # Rationale: Implicit namespace packages are a feature
86
+ "INP001",
87
+
88
+ # Description: Missing documentation
89
+ # Rationale: Important, but secondary concern
90
+ "D100", # Public module
91
+ "D101", # Public class
92
+ "D102", # Public method
93
+ "D103", # Public function
94
+ "D104", # Public package
95
+ "D105", # Magic method
96
+ "D107", # __init__
97
+
98
+ # Description: Use of `assert` detected
99
+ # Rationale: Assertions aren't bad and can be disabled with `python -O`
100
+ "S101",
101
+
102
+ # Description: Missing issue link on the line following this TODO
103
+ # Rationale: Own semantics
104
+ "TD003",
105
+
106
+ # Description: Wildcard imports used
107
+ # Rationale: Waiting for red knot to understand them
108
+ "F403",
109
+
110
+ # Description: Move third-party import into a type-checking block
111
+ # Rationale: Start-up time is not yet that important
112
+ "TC",
113
+
114
+ # Description: Private member accessed
115
+ # Rationale: In reality, this check causes more trouble than prevents bad things
116
+ "SLF001",
117
+
118
+ # Description: Pathlib lints
119
+ # Rationale: Pathlib is intentionally not used
120
+ "PTH",
121
+ ]