Skip to main content

typedparser

build 3.9 status build 3.10 status build 3.11 status build 3.12 status build 3.12 full status build 3.13 status build 3.14 status coverage version

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

  1. Create an attrs class (decorate with @attr.define). Note that optional arguments must also be typed as optional.
  2. Define and type the fields with typedparser.add_argument - the syntax extends add_argument from argparse.
  3. Parse the args with TypedParser and enjoy args with type hints. Disable typechecking by setting strict=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.List and list)
    • Supports positional and keyword arguments in classes
    • Can also typecheck existing attrs instances
    • Allows custom conversions, by default converts source type str to target type Path and int to float
    • Allows to redefine which objects will be recursed into, by default recurses into standard containers (list, dict, etc.)
    • @definenumpy decorator for equality check if the instances contains numpy arrays
  • Some object utilities in typedparser.objects required 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 2 to 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 = True in 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.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for typedparser 0.35.4
File Size Uploaded
typedparser-0.35.4.tar.gz 27.1 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for typedparser 0.35.4
File Interpreter ABI Platform
typedparser-0.35.4-py3-none-any.whl Python 3 none any Details

Total release size: 53.6 kB

Release files / typedparser-0.35.4.tar.gz

Download URL typedparser-0.35.4.tar.gz
Size 27.1 kB
Tags Source
SHA-256 checksum
How to use checksums
1864b2a576d08e07c81ba7f0443cd29420a6e087185e3e874360c2c017800a73
BLAKE2b-256 checksum
How to use checksums
0a866deb1cc8a64cc34eb791485a589150f174d3ce6eeb472d8578aaaf3e5b27
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.4-py3-none-any.whl

Download URL typedparser-0.35.4-py3-none-any.whl
Size 26.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
29685399397a0beef04214814d9be8fef1e62d1f244909525be35596cac9c3b6
BLAKE2b-256 checksum
How to use checksums
0c3553d2a2368b27b0752d248b1c44708a9ab63bc49247f7127b7d4c7442a9d5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.23

Release history Release notifications | RSS feed

This release

0.35.4 This release

2 release files

0.35.3

2 release files

0.35.1

2 release files

0.34.3

2 release files

0.34.2

2 release files

0.34.1

2 release files

0.33.9

2 release files

0.33.8

2 release files

0.33.7

2 release files

0.33.6

2 release files

0.33.5

2 release files

0.33.4

2 release files

0.33.3

2 release files

0.33.2

2 release files

0.33.1

2 release files

0.32.7

2 release files

0.32.6

2 release files

0.32.5

2 release files

0.32.4

2 release files

0.32.2

2 release files

0.32.1

2 release files

0.31.3

2 release files

0.31.2

2 release files

0.31.1

2 release files

0.22.8

2 release files

0.22.7

2 release files

0.22.6

2 release files

0.22.5

2 release files

0.22.4

2 release files

0.22.3

2 release files

0.22.2

2 release files

0.22.1

2 release files

0.18.6

2 release files

0.18.5

2 release files

0.18.3

2 release files

0.18.2

2 release files

0.17.2

2 release files

0.16.2

2 release files

0.13.1

2 release files

0.12.4

2 release files

0.12.3

2 release files

0.12.1

2 release files

0.11.7

2 release files

0.11.6

2 release files

0.11.5

2 release files

0.11.4

2 release files

0.11.3

2 release files

0.11.2

2 release files

0.11.1

2 release files

0.10.6

2 release files

0.10.5

2 release files

0.10.3

2 release files

0.10.2

2 release files

0.10.1

2 release files

0.9.2

2 release files

0.9.1

2 release files

0.8.4

2 release files

0.7.2

2 release files

0.7.1

2 release files

0.6.6

2 release files

0.6.5

2 release files

0.6.4

2 release files

0.6.3

2 release files

0.6.2

2 release files

0.6.1

2 release files

0.5.3

2 release files

0.5.2

2 release files

0.5.1

2 release files

0.4.2

2 release files

0.4.1

2 release files

0.3.12

2 release files

0.3.11

2 release files

0.2.11

2 release files

0.2.9

2 release files

0.2.8

2 release files

0.2.7

2 release files

0.2.4

2 release files

0.2.1

2 release files

0.1.19

2 release files

0.1.15

2 release files

0.1.14

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page