typedparser
Typing extension for python argparse using attrs.
Includes typechecking and conversion utilities to parse a dictionary into an attrs instance.
Install
Requires python>=3.8
pip install typedparser
Basic usage
- Create an attrs class (decorate with
@attr.define). Note that optional arguments must also be typed as optional. - Define and type the fields with
typedparser.add_argument- the syntax extends add_argument from argparse. - Parse the args with
TypedParserand enjoy args with type hints. Disable typechecking by settingstrict=False.
from typing import Optional
from attrs import define
from typedparser import add_argument, TypedParser
@define
class Args:
# omit the argument name to have it inferred from the field name
foo: str = add_argument(positional=True)
bar: int = add_argument(shortcut="-b", type=int, default=0)
opt: Optional[str] = add_argument()
# # in case you prefer the regular argparse syntax:
# foo: str = add_argument("foo")
# bar: int = add_argument("-b", "--bar", type=int, default=0)
# opt: Optional[str] = add_argument("--opt")
def main():
parser = TypedParser.create_parser(Args, strict=True)
args: Args = parser.parse_args()
print(args)
if __name__ == "__main__":
main()
Features
- Create commandline arguments with type hints and checks while staying close to the syntax of the standard library's argparse.
- Utilities for typechecking and converting nested objects:
- Nested checking and conversion of python standard types
- Supports old and new style typing (e.g.
typing.Listandlist) - Supports positional and keyword arguments in classes
- Can also typecheck existing attrs instances
- Allows custom conversions, by default converts source type
strto target typePathandinttofloat - Allows to redefine which objects will be recursed into, by default recurses into standard containers (list, dict, etc.)
@definenumpydecorator for equality check if the instances contains numpy arrays
- Some object utilities in
typedparser.objectsrequired for everything else
Advanced usage
- Use
TypedParser.from_parser(parser, Args)to add typing to an existing parser. This is useful to cover usecases like subparsers or argument groups. - Snippet for argument lists
xarg: List[int] = add_argument(shortcut="-x", type=int, action="append", help="Xarg", default=[]), use as-x 1 -x 2to get[1, 2]in the args instance.
Usage of attr utilities
Define the class hierarchy and parse the input using attrs_from_dict.
Use @define(slots=False) to allow multiple inheritance and setting attributes later.
from attrs import define
from typing import Optional
from typedparser import attrs_from_dict
@define
class Cfg:
foo: int = 12
bar: Optional[int] = None
print(attrs_from_dict(Cfg, {"foo": 1, "bar": 2}))
# Cfg(foo=1, bar=2)
@define
class CfgNested:
sub_cfg: Cfg = None
print(attrs_from_dict(CfgNested, {"sub_cfg": {"foo": 1, "bar": 2}}))
# CfgNested(sub_cfg=Cfg(foo=1, bar=2))
Strict mode (default)
- Convert everything to the target type, e.g. if the input is a list and the annotation is a tuple, the output will be a tuple
- Raise errors if types cannot be matched, there are unknown fields in the input or abstract annotation types are used (e.g. Sequence)
- Set
_allow_extra_keys = Truein the class definition to allow unknown fields in the input
Non-strict mode
Enabled by calling attrs_from_dict with strict=False
- No conversion except for creating the attrs instance from the dict
- Ignore silently if types cannot be matched or abstract annotation types are used
- Unknown fields in the input will be added to the attrs instance if possible (see the hint below about slots)
Skip unknowns
Set skip_unknowns=True to ignore all unknown input fields.
Hints
The following behaviour stems from the attrs package:
- New attributes cannot to be added after class definition to an attrs instance,
unless it is created with
@define(slots=False)Explanation - Untyped fields or "ClassVar" typed fields will be ignored by @attrs.define and therefore also by this library.
Install locally and run tests
Clone repository and cd into. Setup python 3.7 or higher. Note: Some tests are skipped for python 3.7.
pip install -e .
pip install pytest pytest-cov pylint
pylint typedparser
# run tests
python -m pytest --cov
pylint tests
Metadata
Release files for typedparser 0.35.5
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| typedparser-0.35.5.tar.gz | 27.0 kB | Without provenance | Details for typedparser-0.35.5.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| typedparser-0.35.5-py3-none-any.whl | Python 3 | none | any | Details for typedparser-0.35.5-py3-none-any.whl |
Total release size: 53.6 kB
Release files / typedparser-0.35.5.tar.gz
| Download URL | typedparser-0.35.5.tar.gz |
|---|---|
| Size | 27.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
a6f93056cd7c0baca9966cb4c24bc623e6c5c76a735b80f3f5c5577e265a37ed
|
|
BLAKE2b-256 checksum How to use checksums |
4fc570b3c940718eb20fb6ff9f4bea558d4f7433c3352947191f301343fd3377
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.9.23
|
Release files / typedparser-0.35.5-py3-none-any.whl
| Download URL | typedparser-0.35.5-py3-none-any.whl |
|---|---|
| Size | 26.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
d32df84ebc149bdd64c6d2968122475d941f89fc205a754e7610ebece74f4840
|
|
BLAKE2b-256 checksum How to use checksums |
d8ea1515f08b7f0825905daa4c77be8704b7ffa0b5f5891cb1bb206132be4686
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.9.23
|
Security for typedparser 0.35.5
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.