validattr 0.0.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,38 @@
1
+ name: Upload Python Package
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+
7
+ permissions:
8
+ contents: read
9
+
10
+ jobs:
11
+ deploy:
12
+ runs-on: ubuntu-latest
13
+
14
+ steps:
15
+ - name: Checkout
16
+ uses: actions/checkout@v3
17
+ with:
18
+ submodules: recursive
19
+ - name: Set up Python
20
+ uses: actions/setup-python@v3
21
+ with:
22
+ python-version: "3.12.7"
23
+ - name: Upgrade pip
24
+ run: python -m pip install --upgrade pip
25
+ - name: Install yaml
26
+ run: python -m pip install pyyaml
27
+ - name: Install build
28
+ run: python -m pip install build
29
+ - name: Install twine
30
+ run: python -m pip install twine
31
+ - name: Install cfgtools
32
+ run: python -m pip install cfgtools
33
+ - name: Install re-extensions
34
+ run: python -m pip install re-extensions
35
+ - name: Build package
36
+ run: python install.py
37
+ - name: Publish package
38
+ run: twine upload dist/* --username __token__ --password ${{ secrets.PYPI_API_TOKEN }}
@@ -0,0 +1,160 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/#use-with-ide
110
+ .pdm.toml
111
+
112
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113
+ __pypackages__/
114
+
115
+ # Celery stuff
116
+ celerybeat-schedule
117
+ celerybeat.pid
118
+
119
+ # SageMath parsed files
120
+ *.sage.py
121
+
122
+ # Environments
123
+ .env
124
+ .venv
125
+ env/
126
+ venv/
127
+ ENV/
128
+ env.bak/
129
+ venv.bak/
130
+
131
+ # Spyder project settings
132
+ .spyderproject
133
+ .spyproject
134
+
135
+ # Rope project settings
136
+ .ropeproject
137
+
138
+ # mkdocs documentation
139
+ /site
140
+
141
+ # mypy
142
+ .mypy_cache/
143
+ .dmypy.json
144
+ dmypy.json
145
+
146
+ # Pyre type checker
147
+ .pyre/
148
+
149
+ # pytype static type analyzer
150
+ .pytype/
151
+
152
+ # Cython debug symbols
153
+ cython_debug/
154
+
155
+ # PyCharm
156
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
159
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160
+ #.idea/
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2023, Chitaoji
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,42 @@
1
+ Metadata-Version: 2.4
2
+ Name: validattr
3
+ Version: 0.0.0
4
+ Summary: Attribute with validator.
5
+ Project-URL: Documentation, https://github.com/Chitaoji/validattr/blob/main/README.md
6
+ Project-URL: Repository, https://github.com/Chitaoji/validattr/
7
+ Author-email: Chitaoji <2360742040@qq.com>
8
+ Maintainer-email: Chitaoji <2360742040@qq.com>
9
+ License-Expression: BSD-3-Clause
10
+ License-File: LICENSE
11
+ Keywords: config
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Requires-Python: >=3.12
15
+ Description-Content-Type: text/markdown
16
+
17
+ # validattr
18
+ Attribute with validator.
19
+
20
+ ## Installation
21
+ ```sh
22
+ $ pip install validattr
23
+ ```
24
+
25
+ ## Requirements
26
+ ```txt
27
+
28
+ ```
29
+
30
+ ## See Also
31
+ ### Github repository
32
+ * https://github.com/Chitaoji/validattr/
33
+
34
+ ### PyPI project
35
+ * https://pypi.org/project/validattr/
36
+
37
+ ## License
38
+ This project falls under the BSD 3-Clause License.
39
+
40
+ ## History
41
+ ### v0.0.0
42
+ * Initial release.
@@ -0,0 +1,26 @@
1
+ # validattr
2
+ Attribute with validator.
3
+
4
+ ## Installation
5
+ ```sh
6
+ $ pip install validattr
7
+ ```
8
+
9
+ ## Requirements
10
+ ```txt
11
+
12
+ ```
13
+
14
+ ## See Also
15
+ ### Github repository
16
+ * https://github.com/Chitaoji/validattr/
17
+
18
+ ### PyPI project
19
+ * https://pypi.org/project/validattr/
20
+
21
+ ## License
22
+ This project falls under the BSD 3-Clause License.
23
+
24
+ ## History
25
+ ### v0.0.0
26
+ * Initial release.
@@ -0,0 +1,107 @@
1
+ """Install the package."""
2
+
3
+ #!/usr/bin/env python
4
+ # -*- coding: utf-8 -*-
5
+ import os
6
+ import re
7
+ from pathlib import Path
8
+ from typing import Final
9
+
10
+ import cfgtools as cfg
11
+ from re_extensions import rsplit, word_wrap
12
+
13
+ here = Path(__file__).parent
14
+
15
+ # Load the package's meta-data from pyproject.toml.
16
+ f = cfg.read_toml(here / "pyproject.toml")
17
+ project = f["project"].asdict()
18
+ NAME: Final[str] = project["name"]
19
+ SUMMARY: Final[str] = project["description"]
20
+ HOMEPAGE: Final[str] = project["urls"]["Repository"]
21
+ REQUIRES: Final[list[str]] = project["dependencies"]
22
+ SOURCE = "src"
23
+ LICENSE = (here / project["license-files"][0]).read_text().partition("\n")[0]
24
+ VERSION = project["version"]
25
+
26
+ # Import the README and use it as the long-description.
27
+ readme_path = here / project["readme"]
28
+ if readme_path.exists():
29
+ long_description = "\n" + readme_path.read_text(encoding="utf-8")
30
+ else:
31
+ long_description = SUMMARY
32
+
33
+
34
+ def _readme2doc(
35
+ readme: str,
36
+ name: str = NAME,
37
+ requires: list[str] = REQUIRES,
38
+ homepage: str = HOMEPAGE,
39
+ pkg_license: str = LICENSE,
40
+ ) -> tuple[str, str]:
41
+ doc, rd = "", ""
42
+ for i, s in enumerate(rsplit("\n## ", readme)):
43
+ head = re.search(" .*\n", s).group()[1:-1]
44
+ if i == 0:
45
+ s = re.sub("^\n# .*", f"\n# {name}", s)
46
+ elif head == "Requirements":
47
+ s = re.sub(
48
+ "```txt.*```",
49
+ "```txt\n" + "\n".join(requires) + "\n```",
50
+ s,
51
+ flags=re.DOTALL,
52
+ )
53
+ elif head == "Installation":
54
+ s = re.sub(
55
+ "```sh.*```", f"```sh\n$ pip install {name}\n```", s, flags=re.DOTALL
56
+ )
57
+ elif head == "See Also":
58
+ pypipage = f"https://pypi.org/project/{name}/"
59
+ s = re.sub(
60
+ "### PyPI project\n.*",
61
+ f"### PyPI project\n* {pypipage}",
62
+ re.sub(
63
+ "### Github repository\n.*",
64
+ f"### Github repository\n* {homepage}",
65
+ s,
66
+ ),
67
+ )
68
+ elif head == "License":
69
+ s = f"\n## License\nThis project falls under the {pkg_license}.\n"
70
+
71
+ rd += s
72
+ if head not in {"Installation", "Requirements", "History"}:
73
+ doc += s
74
+ doc = re.sub("<!--html-->.*<!--/html-->", "", doc, flags=re.DOTALL)
75
+ return word_wrap(doc, maximum=88) + "\n\n", rd
76
+
77
+
78
+ def _quote(readme: str) -> str:
79
+ if "'''" in readme and '"""' in readme:
80
+ raise ReadmeFormatError("Both \"\"\" and ''' are found in the README")
81
+ if '"""' in readme:
82
+ return f"'''{readme}'''"
83
+ else:
84
+ return f'"""{readme}"""'
85
+
86
+
87
+ def _version(version: str = VERSION) -> str:
88
+ return f'"""Version file."""\n\n__version__ = "{version}"\n'
89
+
90
+
91
+ class ReadmeFormatError(Exception):
92
+ """Raised when the README has a wrong format."""
93
+
94
+
95
+ if __name__ == "__main__":
96
+ # Import the __init__.py and change the module docstring.
97
+ init_path = here / SOURCE / NAME / "__init__.py"
98
+ version_path = here / SOURCE / NAME / "_version.py"
99
+ module_file = init_path.read_text(encoding="utf-8")
100
+ new_doc, long_description = _readme2doc(long_description)
101
+ module_file = re.sub(
102
+ "^\"\"\".*\"\"\"|^'''.*'''|^", _quote(new_doc), module_file, flags=re.DOTALL
103
+ )
104
+ init_path.write_text(module_file, encoding="utf-8")
105
+ readme_path.write_text(long_description.strip(), encoding="utf-8")
106
+ version_path.write_text(_version())
107
+ os.system(f"cd {here} && python -m build")
@@ -0,0 +1,28 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "validattr"
7
+ version = "0.0.0"
8
+ dependencies = []
9
+ requires-python = ">=3.12"
10
+ authors = [
11
+ {name = "Chitaoji", email = "2360742040@qq.com"},
12
+ ]
13
+ maintainers = [
14
+ {name = "Chitaoji", email = "2360742040@qq.com"}
15
+ ]
16
+ description = "Attribute with validator."
17
+ readme = "README.md"
18
+ license = "BSD-3-Clause"
19
+ license-files = ["LICENSE"]
20
+ keywords = ["config"]
21
+ classifiers = [
22
+ "Programming Language :: Python :: 3",
23
+ "Programming Language :: Python :: 3.12"
24
+ ]
25
+
26
+ [project.urls]
27
+ Documentation = "https://github.com/Chitaoji/validattr/blob/main/README.md"
28
+ Repository = "https://github.com/Chitaoji/validattr/"
@@ -0,0 +1,22 @@
1
+ """
2
+ # validattr
3
+ Attribute with validator.
4
+
5
+ ## See Also
6
+ ### Github repository
7
+ * https://github.com/Chitaoji/validattr/
8
+
9
+ ### PyPI project
10
+ * https://pypi.org/project/validattr/
11
+
12
+ ## License
13
+ This project falls under the BSD 3-Clause License.
14
+
15
+ """
16
+
17
+ from . import core
18
+ from ._version import __version__
19
+ from .core import *
20
+
21
+ __all__: list[str] = []
22
+ __all__.extend(core.__all__)
@@ -0,0 +1,10 @@
1
+ """
2
+ Contains typing classes.
3
+
4
+ NOTE: this module is not intended to be imported at runtime.
5
+
6
+ """
7
+
8
+ import loggings
9
+
10
+ loggings.warning("this module is not intended to be imported at runtime")
@@ -0,0 +1,3 @@
1
+ """Version file."""
2
+
3
+ __version__ = "0.0.0"
@@ -0,0 +1,454 @@
1
+ """
2
+ Contains the core of validattr.
3
+
4
+ NOTE: this module is private. All functions and objects are available in the main
5
+ `validattr` namespace - use that instead.
6
+
7
+ """
8
+
9
+ from dataclasses import Field, field
10
+ from types import UnionType
11
+ from typing import Any, Callable, Literal, Optional, Union, get_args, get_origin
12
+
13
+ __all__ = ["attr", "ValidatorError"]
14
+
15
+
16
+ def attr(
17
+ *,
18
+ default: Any = ...,
19
+ default_factory: Callable[[], Any] = ...,
20
+ allowlist: list = ...,
21
+ denylist: list = ...,
22
+ validator: Callable[[Any], bool] = ...,
23
+ lb: Any = ...,
24
+ ub: Any = ...,
25
+ init: bool = True,
26
+ repr: bool = True,
27
+ hash: Optional[bool] = None,
28
+ compare: bool = True,
29
+ kw_only: bool = False,
30
+ ) -> Any:
31
+ """
32
+ Returns an attribute with validator. This works well with dataclasses.
33
+
34
+ Only for dict classes.
35
+
36
+ Parameters
37
+ ----------
38
+ default : Any, optional
39
+ Default value, by default Ellipsis.
40
+ default_factory : Callable[[], Any], optional
41
+ Callable used to generate a default value lazily, by default Ellipsis.
42
+ allowlist : list, optional
43
+ Allowed values, by default Ellipsis.
44
+ denylist : list, optional
45
+ Forbidden values, by default Ellipsis.
46
+ lb : Any, optional
47
+ Lower bound (inclusive), by default Ellipsis.
48
+ ub : Any, optional
49
+ Upper bound (inclusive), by default Ellipsis.
50
+ validator : Callable[[Any], bool], optional
51
+ Function for validating the value, by default Ellipsis.
52
+ init : bool, optional
53
+ Whether this field should be included as a generated `__init__()`
54
+ parameter when used with `dataclasses.dataclass`, by default True.
55
+ repr : bool, optional
56
+ Whether this field should be included in the generated `__repr__()`
57
+ output, by default True.
58
+ hash : Optional[bool], optional
59
+ Whether this field should be included in generated `__hash__()`.
60
+ Follows `dataclasses.field` behavior where `None` defers to
61
+ `compare`, by default None.
62
+ compare : bool, optional
63
+ Whether this field should be used in generated comparison methods,
64
+ by default True.
65
+ kw_only : bool, optional
66
+ Whether this field should be marked as keyword-only for
67
+ `dataclasses.dataclass` generated `__init__()`, by default False.
68
+
69
+ Returns
70
+ -------
71
+ Any
72
+ Attribute with validator.
73
+
74
+ """
75
+ descriptor = AttrValidator(
76
+ default=default,
77
+ default_factory=default_factory,
78
+ allowlist=allowlist,
79
+ denylist=denylist,
80
+ lb=lb,
81
+ ub=ub,
82
+ validator=validator,
83
+ )
84
+ if not isinstance(init, bool):
85
+ raise ValidatorError(
86
+ f"invalid init type: expected a bool, got {type(init)!r} instead"
87
+ )
88
+ if not isinstance(repr, bool):
89
+ raise ValidatorError(
90
+ f"invalid repr type: expected a bool, got {type(repr)!r} instead"
91
+ )
92
+ if hash is not None and not isinstance(hash, bool):
93
+ raise ValidatorError(
94
+ f"invalid hash type: expected a bool or None, got {type(hash)!r} instead"
95
+ )
96
+ if not isinstance(compare, bool):
97
+ raise ValidatorError(
98
+ f"invalid compare type: expected a bool, got {type(compare)!r} instead"
99
+ )
100
+ if not isinstance(kw_only, bool):
101
+ raise ValidatorError(
102
+ f"invalid kw_only type: expected a bool, got {type(kw_only)!r} instead"
103
+ )
104
+ return _field_with_guard(
105
+ default=descriptor,
106
+ init=init,
107
+ repr=repr,
108
+ hash=hash,
109
+ compare=compare,
110
+ kw_only=kw_only,
111
+ )
112
+
113
+
114
+ class _FieldWithGuard(Field):
115
+ def __get__(self, instance: object, owner: type | None = None) -> Any:
116
+ if instance is None:
117
+ return self
118
+ return self.default.__get__(instance, owner)
119
+
120
+ def __set__(self, instance: object, value: Any) -> None:
121
+ return self.default.__set__(instance, value)
122
+
123
+
124
+ def _field_with_guard(
125
+ *,
126
+ default: Any,
127
+ init: bool,
128
+ repr: bool,
129
+ hash: Optional[bool],
130
+ compare: bool,
131
+ kw_only: bool,
132
+ ) -> Any:
133
+ base_field = field(
134
+ default=default,
135
+ init=init,
136
+ repr=repr,
137
+ hash=hash,
138
+ compare=compare,
139
+ kw_only=kw_only,
140
+ )
141
+ guarded_field = _FieldWithGuard(
142
+ base_field.default,
143
+ base_field.default_factory,
144
+ base_field.init,
145
+ base_field.repr,
146
+ base_field.hash,
147
+ base_field.compare,
148
+ base_field.metadata,
149
+ base_field.kw_only,
150
+ )
151
+ guarded_field._field_type = base_field._field_type
152
+ return guarded_field
153
+
154
+
155
+ class AttrValidator:
156
+ """
157
+ Attribute validator.
158
+
159
+ Note that this should NEVER be instantiated directly, but always through the
160
+ module-level function `attr()`.
161
+
162
+ """
163
+
164
+ def __init__(
165
+ self,
166
+ *,
167
+ default: Any = ...,
168
+ default_factory: Callable[[], Any] = ...,
169
+ allowlist: list = ...,
170
+ denylist: list = ...,
171
+ lb: Any = ...,
172
+ ub: Any = ...,
173
+ validator: Callable[[Any], bool] = ...,
174
+ ) -> None:
175
+ self.default = default
176
+ if default is not ... and default_factory is not ...:
177
+ raise ValidatorError(
178
+ "invalid defaults: default and default_factory cannot both be set"
179
+ )
180
+ if default_factory is not ... and not callable(default_factory):
181
+ raise ValidatorError(
182
+ "invalid default_factory type: expected a callable, "
183
+ f"got {type(default_factory)!r} instead"
184
+ )
185
+ self.default_factory = default_factory
186
+ if allowlist is not ... and not isinstance(allowlist, list):
187
+ raise ValidatorError(
188
+ f"invalid allowlist type: expected a list, got {type(allowlist)!r} "
189
+ "instead"
190
+ )
191
+ if denylist is not ... and not isinstance(denylist, list):
192
+ raise ValidatorError(
193
+ f"invalid denylist type: expected a list, got {type(denylist)!r} "
194
+ "instead"
195
+ )
196
+ self.allowlist = allowlist
197
+ self.denylist = denylist
198
+ self.lb = lb
199
+ self.ub = ub
200
+ if self.lb is not ... and self.ub is not ... and self.lb > self.ub:
201
+ raise ValidatorError(
202
+ f"invalid bounds: lb={self.lb!r} is greater than ub={self.ub!r}"
203
+ )
204
+ self.validator = (lambda _: True) if validator is ... else validator
205
+ self.name: str
206
+ self.type: type
207
+
208
+ def __set_name__(self, cls: type, name: str) -> None:
209
+ self.name = name
210
+ self.type = cls.__annotations__[name]
211
+ self._validate_allowlist(cls)
212
+ self._validate_default(cls)
213
+
214
+ def _validate_default(self, cls: type) -> None:
215
+ if self.default_factory is not ...:
216
+ default = self.default_factory()
217
+ mismatch_reason = isoftype(
218
+ default,
219
+ self.type,
220
+ self.name,
221
+ path="default_factory() expected",
222
+ )
223
+ if mismatch_reason is not None:
224
+ raise ValidatorError(
225
+ f"invalid default_factory return type for {cls.__name__}.{self.name}: "
226
+ f"{mismatch_reason}"
227
+ )
228
+ self._validate_bounds(cls, default, "default_factory()")
229
+ self._validate_default_membership(cls, default, "default_factory()")
230
+ return
231
+ if self.default is ...:
232
+ return
233
+ mismatch_reason = isoftype(self.default, self.type, self.name, path="expected")
234
+ if mismatch_reason is not None:
235
+ raise ValidatorError(
236
+ f"invalid default type for {cls.__name__}.{self.name}: {mismatch_reason}"
237
+ )
238
+ self._validate_bounds(cls, self.default, "default")
239
+ self._validate_default_membership(cls, self.default, "default")
240
+
241
+ def _validate_allowlist(self, cls: type) -> None:
242
+ if self.allowlist is ...:
243
+ return
244
+ if not isinstance(self.allowlist, list):
245
+ raise ValidatorError(
246
+ f"invalid allowlist type of {cls.__name__}.{self.name}: "
247
+ f"expected a list, got {type(self.allowlist)!r} instead"
248
+ )
249
+ for idx, item in enumerate(self.allowlist):
250
+ mismatch_reason = isoftype(
251
+ item,
252
+ self.type,
253
+ self.name,
254
+ path=f"allowlist[{idx}] expected",
255
+ )
256
+ if mismatch_reason is not None:
257
+ raise ValidatorError(
258
+ f"invalid allowlist type of {cls.__name__}.{self.name}: "
259
+ + mismatch_reason
260
+ )
261
+ self._validate_bounds(cls, item, f"allowlist[{idx}]")
262
+
263
+ def _validate_default_membership(
264
+ self, cls: type, value: Any, value_name: str
265
+ ) -> None:
266
+ if self.allowlist is not ... and value not in self.allowlist:
267
+ raise ValidatorError(
268
+ f"invalid {value_name} value for {cls.__name__}.{self.name}: "
269
+ f"expected value in {self.allowlist!r}, "
270
+ f"got {value!r} instead"
271
+ )
272
+ if self.denylist is not ... and value in self.denylist:
273
+ raise ValidatorError(
274
+ f"invalid {value_name} value for {cls.__name__}.{self.name}: "
275
+ f"expected value not in {self.denylist!r}, "
276
+ f"but got {value!r}"
277
+ )
278
+
279
+ def _validate_bounds(self, cls: type, value: Any, value_name: str) -> None:
280
+ if self.lb is not ... and value < self.lb:
281
+ raise ValidatorError(
282
+ f"invalid value for {value_name} of {cls.__name__}.{self.name}: "
283
+ f"expected value >= {self.lb!r}, got {value!r} instead"
284
+ )
285
+ if self.ub is not ... and value > self.ub:
286
+ raise ValidatorError(
287
+ f"invalid value for {value_name} of {cls.__name__}.{self.name}: "
288
+ f"expected value <= {self.ub!r}, got {value!r} instead"
289
+ )
290
+
291
+ def __set__(self, instance: object, value: Any) -> None:
292
+ if isinstance(value, self.__class__):
293
+ if self.default is ... and self.default_factory is ...:
294
+ raise TypeError(
295
+ f"{instance.__class__.__name__}.__init__() missing 1 required "
296
+ f"positional argument: {self.name!r}"
297
+ )
298
+ return
299
+ mismatch_reason = isoftype(value, self.type, self.name)
300
+ if mismatch_reason is not None:
301
+ raise TypeError(
302
+ f"invalid type for {instance.__class__.__name__}.{self.name}: "
303
+ + mismatch_reason
304
+ )
305
+ if self.allowlist is not ...:
306
+ if value not in self.allowlist:
307
+ raise ValueError(
308
+ f"invalid value for {instance.__class__.__name__}.{self.name}: "
309
+ f"expected value in {self.allowlist!r}, got {value!r} instead"
310
+ )
311
+ if self.denylist is not ...:
312
+ if value in self.denylist:
313
+ raise ValueError(
314
+ f"invalid value for {instance.__class__.__name__}.{self.name}: "
315
+ f"expected value not in {self.denylist!r}, but got {value!r}"
316
+ )
317
+ if self.lb is not ... and value < self.lb:
318
+ raise ValueError(
319
+ f"invalid value for {instance.__class__.__name__}.{self.name}: "
320
+ f"expected value >= {self.lb!r}, got {value!r} instead"
321
+ )
322
+ if self.ub is not ... and value > self.ub:
323
+ raise ValueError(
324
+ f"invalid value for {instance.__class__.__name__}.{self.name}: "
325
+ f"expected value <= {self.ub!r}, got {value!r} instead"
326
+ )
327
+ if not self.validator(value):
328
+ raise ValueError(f"invalid value for {self.name!r}: {value}")
329
+ instance.__dict__[self.name] = value
330
+
331
+ def __get__(self, instance: object, owner: type) -> Any:
332
+ if not instance:
333
+ return self
334
+ if self.name not in instance.__dict__:
335
+ if self.default_factory is not ...:
336
+ self.__set__(instance, self.default_factory())
337
+ elif self.default is ...:
338
+ raise AttributeError(
339
+ f"{owner.__name__!r} object has no attribute {self.name!r}"
340
+ )
341
+ else:
342
+ self.__set__(instance, self.default)
343
+ return instance.__dict__[self.name]
344
+
345
+ def __delete__(self, instance: object) -> None:
346
+ del instance.__dict__[self.name]
347
+
348
+
349
+ def isoftype(
350
+ value: object, type_hint: type, name: str, path: str = "expected"
351
+ ) -> Optional[str]:
352
+ """
353
+ Returns a detailed mismatch message when `value` does not satisfy `type_hint`.
354
+
355
+ Parameters
356
+ ----------
357
+ value : object
358
+ Value to be checked.
359
+ type_hint : type
360
+ Type hint object.
361
+ name: str
362
+ Variable name.
363
+ path : str, optional
364
+ Human-readable value path used in the error details.
365
+
366
+ Returns
367
+ -------
368
+ Optional[str]
369
+ None when the check passes; otherwise a description of the mismatch.
370
+
371
+ """
372
+ origin = get_origin(type_hint)
373
+ args = get_args(type_hint)
374
+
375
+ if type_hint is Any:
376
+ return None
377
+
378
+ if origin is None:
379
+ if isinstance(value, type_hint):
380
+ return None
381
+ return f"{path} {type_hint!r}, got {type(value)!r} instead"
382
+
383
+ if origin is Union or origin is UnionType:
384
+ union_errors = [isoftype(value, arg, name, path) for arg in args]
385
+ if any(error is None for error in union_errors):
386
+ return None
387
+ return f"{path} one of {args}, got {value.__class__!r} instead"
388
+
389
+ if origin is Literal:
390
+ if value in args:
391
+ return None
392
+ return f"{path} one of {args!r}, got {value!r} instead"
393
+
394
+ if origin is list:
395
+ (elem_type,) = args
396
+ if not isinstance(value, list):
397
+ return f"{path} a list, got {type(value)!r} instead"
398
+ for idx, elem in enumerate(value):
399
+ elem_error = isoftype(elem, elem_type, name, f"{name}[{idx}] expected")
400
+ if elem_error is not None:
401
+ return elem_error
402
+ return None
403
+
404
+ if origin is tuple:
405
+ if len(args) == 2 and args[1] is Ellipsis:
406
+ (elem_type, _) = args
407
+ if not isinstance(value, tuple):
408
+ return f"{path} a tuple, got {type(value)!r} instead"
409
+ for idx, elem in enumerate(value):
410
+ elem_error = isoftype(elem, elem_type, name, f"{name}[{idx}] expected")
411
+ if elem_error is not None:
412
+ return elem_error
413
+ return None
414
+
415
+ if not isinstance(value, tuple) or len(value) != len(args):
416
+ return (
417
+ f"{path} a tuple with {len(args)} elements, got {type(value)!r} with "
418
+ f"length {len(value) if isinstance(value, tuple) else 'N/A'} instead"
419
+ )
420
+ for idx, (elem, elem_type) in enumerate(zip(value, args)):
421
+ elem_error = isoftype(elem, elem_type, name, f"{name}[{idx}] expected")
422
+ if elem_error is not None:
423
+ return elem_error
424
+ return None
425
+
426
+ if origin is dict:
427
+ key_t, val_t = args
428
+ if not isinstance(value, dict):
429
+ return f"{path} a dict, got {type(value)!r} instead"
430
+ for key, val in value.items():
431
+ key_error = isoftype(
432
+ key, key_t, name, f"{name}.keys() element {key!r} expected"
433
+ )
434
+ if key_error is not None:
435
+ return key_error
436
+ val_error = isoftype(val, val_t, name, f"{name}[{key!r}] expected")
437
+ if val_error is not None:
438
+ return val_error
439
+ return None
440
+
441
+ if origin is set:
442
+ (elem_type,) = args
443
+ if not isinstance(value, set):
444
+ return f"{path} a set, got {type(value)!r} instead"
445
+ for elem in value:
446
+ elem_error = isoftype(elem, elem_type, name, f"{path} element {elem!r}")
447
+ if elem_error is not None:
448
+ return elem_error
449
+ return None
450
+
451
+ raise NotImplementedError(f"Unsupported type hint: {type_hint}")
452
+
453
+
454
+ class ValidatorError(RuntimeError): ...
@@ -0,0 +1,283 @@
1
+ import unittest
2
+ from dataclasses import dataclass
3
+ from typing import Any, Literal
4
+
5
+ from src.validattr import ValidatorError, attr
6
+
7
+
8
+ class TestAttrWithDataclasses(unittest.TestCase):
9
+ def test_default_value_is_lazily_applied(self):
10
+ @dataclass
11
+ class Config:
12
+ retries: int = attr(default=3)
13
+
14
+ cfg = Config()
15
+ self.assertEqual(cfg.retries, 3)
16
+
17
+ def test_missing_value_without_default_raises(self):
18
+ @dataclass
19
+ class Config:
20
+ retries: int = attr()
21
+
22
+ with self.assertRaisesRegex(
23
+ TypeError,
24
+ r"Config.__init__\(\) missing 1 required positional argument: 'retries'",
25
+ ):
26
+ Config()
27
+
28
+ def test_type_validation_for_builtin_and_assignment(self):
29
+ @dataclass
30
+ class User:
31
+ age: int = attr()
32
+
33
+ with self.assertRaises(TypeError):
34
+ User(age="20")
35
+
36
+ u = User(age=20)
37
+ with self.assertRaises(TypeError):
38
+ u.age = "bad"
39
+
40
+ def test_allowlist_and_denylist(self):
41
+ @dataclass
42
+ class Role:
43
+ name: str = attr(allowlist=["admin", "guest"], denylist=["guest"])
44
+
45
+ with self.assertRaises(ValueError):
46
+ Role(name="user")
47
+
48
+ with self.assertRaises(ValueError):
49
+ Role(name="guest")
50
+
51
+ obj = Role(name="admin")
52
+ self.assertEqual(obj.name, "admin")
53
+
54
+ def test_bounds_validation(self):
55
+ @dataclass
56
+ class RangeCfg:
57
+ score: int = attr(lb=0, ub=100)
58
+
59
+ with self.assertRaises(ValueError):
60
+ RangeCfg(score=-1)
61
+
62
+ with self.assertRaises(ValueError):
63
+ RangeCfg(score=101)
64
+
65
+ self.assertEqual(RangeCfg(score=60).score, 60)
66
+
67
+ def test_custom_validator(self):
68
+ @dataclass
69
+ class EvenCfg:
70
+ value: int = attr(validator=lambda x: x % 2 == 0)
71
+
72
+ self.assertEqual(EvenCfg(value=10).value, 10)
73
+ with self.assertRaises(ValueError):
74
+ EvenCfg(value=11)
75
+
76
+ def test_constructor_parameter_validation(self):
77
+ with self.assertRaises(ValidatorError):
78
+ attr(allowlist=(1, 2, 3))
79
+
80
+ with self.assertRaises(ValidatorError):
81
+ attr(denylist=(1, 2, 3))
82
+
83
+ with self.assertRaises(ValidatorError):
84
+ attr(lb=10, ub=1)
85
+
86
+ def test_allowlist_element_type_check(self):
87
+ with self.assertRaises(RuntimeError):
88
+
89
+ @dataclass
90
+ class BadAllowlist:
91
+ value: int = attr(allowlist=[1, "2"])
92
+
93
+ def test_denylist_element_type_is_not_checked_on_class_init(self):
94
+ @dataclass
95
+ class BadDenylist:
96
+ value: int = attr(denylist=[1, "2"])
97
+
98
+ obj = BadDenylist(value=2)
99
+ self.assertEqual(obj.value, 2)
100
+
101
+ def test_default_type_check_on_class_init(self):
102
+ with self.assertRaises(RuntimeError):
103
+
104
+ @dataclass
105
+ class BadDefault:
106
+ value: int = attr(default="1")
107
+
108
+ def test_default_bound_check_on_class_init(self):
109
+ with self.assertRaises(RuntimeError):
110
+
111
+ @dataclass
112
+ class BadDefaultBound:
113
+ value: int = attr(default=0, lb=1)
114
+
115
+ def test_default_allowlist_membership_check_on_class_init(self):
116
+ with self.assertRaises(RuntimeError):
117
+
118
+ @dataclass
119
+ class BadDefaultAllowlist:
120
+ value: int = attr(default=3, allowlist=[1, 2])
121
+
122
+ def test_default_denylist_membership_check_on_class_init(self):
123
+ with self.assertRaises(RuntimeError):
124
+
125
+ @dataclass
126
+ class BadDefaultDenylist:
127
+ value: int = attr(default=2, denylist=[1, 2])
128
+
129
+ def test_allowlist_bound_check_on_class_init(self):
130
+ with self.assertRaises(RuntimeError):
131
+
132
+ @dataclass
133
+ class BadAllowlistBound:
134
+ value: int = attr(allowlist=[1, 2], ub=1)
135
+
136
+ def test_class_level_descriptor_access_and_any_type(self):
137
+ @dataclass
138
+ class GenericCfg:
139
+ payload: Any = attr(default={"ok": True})
140
+
141
+ self.assertIsNotNone(GenericCfg.payload)
142
+ cfg = GenericCfg()
143
+ cfg.payload = object()
144
+ self.assertIsNotNone(cfg.payload)
145
+
146
+ def test_union_literal_and_collections(self):
147
+ @dataclass
148
+ class ComplexCfg:
149
+ token: int | str = attr()
150
+ mode: Literal["dev", "prod"] = attr()
151
+ nums: list[int] = attr()
152
+ point: tuple[int, int] = attr()
153
+ tags: tuple[str, ...] = attr(default=("ok",))
154
+ mapping: dict[str, int] = attr()
155
+ uniq: set[int] = attr()
156
+
157
+ cfg = ComplexCfg(
158
+ token="a",
159
+ mode="dev",
160
+ nums=[1, 2],
161
+ point=(3, 4),
162
+ mapping={"x": 1},
163
+ uniq={1, 2},
164
+ )
165
+ self.assertEqual(cfg.tags, ("ok",))
166
+
167
+ with self.assertRaises(TypeError):
168
+ cfg.mode = "qa"
169
+
170
+ with self.assertRaises(TypeError):
171
+ cfg.nums = [1, "2"]
172
+
173
+ with self.assertRaises(TypeError):
174
+ cfg.point = (1, 2, 3)
175
+
176
+ with self.assertRaises(TypeError):
177
+ cfg.mapping = {1: 2}
178
+
179
+ with self.assertRaises(TypeError):
180
+ cfg.uniq = {1, "2"}
181
+
182
+ def test_delete_attribute(self):
183
+ @dataclass
184
+ class Config:
185
+ retries: int = attr(default=3)
186
+
187
+ cfg = Config()
188
+ self.assertEqual(cfg.retries, 3)
189
+ del cfg.retries
190
+ self.assertEqual(cfg.retries, 3)
191
+
192
+ def test_default_factory_produces_per_instance_value(self):
193
+ @dataclass
194
+ class Config:
195
+ payload: list[int] = attr(default_factory=list)
196
+
197
+ first = Config()
198
+ second = Config()
199
+ first.payload.append(1)
200
+ self.assertEqual(first.payload, [1])
201
+ self.assertEqual(second.payload, [])
202
+
203
+ def test_default_and_default_factory_cannot_be_set_together(self):
204
+ with self.assertRaises(ValidatorError):
205
+ attr(default=1, default_factory=lambda: 1)
206
+
207
+ def test_default_factory_type_check_on_class_init(self):
208
+ with self.assertRaises(RuntimeError):
209
+
210
+ @dataclass
211
+ class BadDefaultFactory:
212
+ value: int = attr(default_factory=lambda: "1")
213
+
214
+ def test_init_false_excludes_parameter_and_keeps_default(self):
215
+ @dataclass
216
+ class Config:
217
+ retries: int = attr(default=3, init=False)
218
+
219
+ cfg = Config()
220
+ self.assertEqual(cfg.retries, 3)
221
+
222
+ with self.assertRaises(TypeError):
223
+ Config(retries=10)
224
+
225
+ def test_init_option_must_be_bool(self):
226
+ with self.assertRaises(ValidatorError):
227
+ attr(init=1)
228
+
229
+ def test_repr_option_controls_dataclass_repr(self):
230
+ @dataclass
231
+ class Config:
232
+ visible: int = attr(default=1)
233
+ hidden: int = attr(default=2, repr=False)
234
+
235
+ config_repr = repr(Config())
236
+ self.assertIn("visible=1", config_repr)
237
+ self.assertNotIn("hidden=2", config_repr)
238
+
239
+ def test_compare_option_controls_equality(self):
240
+ @dataclass
241
+ class Config:
242
+ stable: int = attr(default=1)
243
+ volatile: int = attr(default=1, compare=False)
244
+
245
+ self.assertEqual(Config(stable=1, volatile=1), Config(stable=1, volatile=2))
246
+
247
+ def test_hash_option_controls_hashing(self):
248
+ @dataclass(unsafe_hash=True)
249
+ class Config:
250
+ included: int = attr(default=1, hash=True)
251
+ skipped: int = attr(default=1, hash=False)
252
+
253
+ self.assertEqual(
254
+ hash(Config(included=1, skipped=1)),
255
+ hash(Config(included=1, skipped=2)),
256
+ )
257
+
258
+ def test_kw_only_option_requires_keyword_argument(self):
259
+ @dataclass
260
+ class Config:
261
+ positional: int = attr()
262
+ keyword_only: int = attr(kw_only=True)
263
+
264
+ self.assertEqual(Config(1, keyword_only=2).keyword_only, 2)
265
+ with self.assertRaises(TypeError):
266
+ Config(1, 2)
267
+
268
+ def test_repr_hash_compare_kw_only_options_must_be_bool_or_none(self):
269
+ with self.assertRaises(ValidatorError):
270
+ attr(repr=1)
271
+
272
+ with self.assertRaises(ValidatorError):
273
+ attr(hash="bad")
274
+
275
+ with self.assertRaises(ValidatorError):
276
+ attr(compare=1)
277
+
278
+ with self.assertRaises(ValidatorError):
279
+ attr(kw_only=1)
280
+
281
+
282
+ if __name__ == "__main__":
283
+ unittest.main()