Typed-argument-parser

Latest version: v1.10.0

Safety actively analyzes 621521 Python packages for vulnerabilities to keep your Python projects secure.

Scan your dependencies

Page 1 of 4

7.0

This was implemented in https://github.com/swansonk14/typed-argument-parser/pull/66 and addresses https://github.com/swansonk14/typed-argument-parser/issues/64.

Other Changes

ea8254d6a4042b6339e6a41ca0f7cfe772c98848 Exposed `argparse`'s errors `ArgumentError` and `ArgumentTypeError` through Tap so that they can be imported directly with `from tap import ArgumentError` rather than `from argparse import ArgumentError`. This addresses https://github.com/swansonk14/typed-argument-parser/issues/46.

b1f909a2a1bd748082cde4f01dc4335fd1d56eb7 Changed the name of the `master` branch to `main`.

https://github.com/swansonk14/typed-argument-parser/pull/60 https://github.com/swansonk14/typed-argument-parser/pull/61 https://github.com/swansonk14/typed-argument-parser/pull/62 Added shlex support for config files to allow quoted strings and comments, building on https://github.com/swansonk14/typed-argument-parser/issues/51.

1.10.0

Pydantic [Models](https://docs.pydantic.dev/latest/concepts/models/) and [dataclasses](https://docs.pydantic.dev/latest/concepts/dataclasses/) can now be `tapify`d.

python
square_pydantic.py
from pydantic import BaseModel, Field

from tap import tapify

class Squarer(BaseModel):
"""Squarer with a number to square."""
num: float = Field(description="The number to square.")

def get_square(self) -> float:
"""Get the square of the number."""
return self.num ** 2

if __name__ == '__main__':
squarer = tapify(Squarer)
print(f'The square of your number is {squarer.get_square()}.')


For Pydantic v2 models and dataclasses, the argument's description (which is displayed in the `-h` help message) can
either be specified in the class docstring or the field's `description`. If both are specified, the description from the
docstring is used. In the example below, the description is provided in the docstring.

For Pydantic v1 models and dataclasses, the argument's description must be provided in the class docstring:

python
square_pydantic.py
from pydantic import BaseModel

from tap import tapify

class Squarer(BaseModel):
"""Squarer with a number to square.

:param num: The number to square.
"""
num: float

def get_square(self) -> float:
"""Get the square of the number."""
return self.num ** 2

if __name__ == '__main__':
squarer = tapify(Squarer)
print(f'The square of your number is {squarer.get_square()}.')

1.9.0

Python 3.12 Support, Better Support for `tapify`, Bug Fixes

Python 3.12 Support

https://github.com/swansonk14/typed-argument-parser/commit/ee488632f29909d9a992fe6e13a95058b36a06d0: AlexWaygood introduced support for Python 3.12 (https://github.com/swansonk14/typed-argument-parser/pull/122).

Better Support for `tapify`

https://github.com/swansonk14/typed-argument-parser/commit/612fabe1d13c1c9227f43b1910998630c40d07f3: shorie000 corrected the signature of `tapify` to indicate that it accepts a class type rather than a class object as input (https://github.com/swansonk14/typed-argument-parser/pull/119).

https://github.com/swansonk14/typed-argument-parser/commit/80735dcd80a62f4a27433adcb5a37ac0cfa5fc2a: Resolved an issue in `tapify` (https://github.com/swansonk14/typed-argument-parser/issues/114) so that it can now handle `**kwargs` in function and class definitions.

python
main.py
from tap import tapify

def foo(a: int, b: int = 2, **kwargs) -> str:
print(f"sum = {a + b}")
for key, value in kwargs.items():
print(f"{key}: {value}")

if __name__ == "__main__":
tapify(concat)


Running `python main.py --a 1 --b 3 --c kwa --d arg` will print:


sum = 4
c: kwa
d: arg


Note that all keys and values in kwargs will be strings.

Bug Fixes

https://github.com/swansonk14/typed-argument-parser/commit/18b13d18e69dc948a3a8cc6b5372f25ccf5d3499: Resolved an issue in `Tap` (https://github.com/swansonk14/typed-argument-parser/issues/118) where tuples of Literals are parsed incorrectly.

Now, code such as the following example will run correctly.

python
from tap import Tap
from typing import Literal

class Args(Tap):
arg: tuple[Literal['a', 'b'], ...]

args = Args().parse_args(['--arg', 'a', 'b'])


https://github.com/swansonk14/typed-argument-parser/commit/70137fd810e715c1ae30c32e8c2ff5cd5f77aa98: Resolved an issue where arguments in dynamically created Tap classes have help strings that display arguments in the wrong order (https://github.com/swansonk14/typed-argument-parser/issues/121).

1.8.1

Summer Cleaning

This release contains a few small bug fixes.

68cd6f4c22340ed97b024556676ba3f456e136ee: In `save`, fixes threading of the argument `repo_path` so that it is used.

d26f0b8be624b966635e40e0f3c3b4f8e0894b93: Changes the type hints of all path-like arguments (e.g., `path` in the method `save`) to support both `str` and `pathlib.Path`.

c48ef74a489917fbb3ab9dea1ffed6c08c112bd7: Drops support for Python 3.7 due to end-of-life and removes the dependency on `typing_extensions` (since the `Literal` type is built into Python 3.8+).

7f12646b22157114832ad0a86dd430ca1977a2d7, 33e7c5311836d4d6d85beb0645b2549652966a03, 33e7c5311836d4d6d85beb0645b2549652966a03: Moves the `deepcopy` of default arguments to avoid pickle errors.

33e7c5311836d4d6d85beb0645b2549652966a03, 33e7c5311836d4d6d85beb0645b2549652966a03: Fixes bugs that we introduced in the above commits ;)

1.8.0

Tapify

`tapify` makes it possible to run functions or initialize objects via command line arguments. This is inspired by Google's [Python Fire](https://github.com/google/python-fire), but `tapify` also automatically casts command line arguments to the appropriate types based on the type hints. Under the hood, `tapify` implicitly creates a Tap object and uses it to parse the command line arguments, which it then uses to run the function or initialize the class. We show a few examples below.

Examples

Function

python
square_function.py
from tap import tapify

def square(num: float) -> float:
"""Square a number.

:param num: The number to square.
"""
return num ** 2

if __name__ == '__main__':
squared = tapify(square)
print(f'The square of your number is {squared}.')


Running `python square_function.py --num 5` prints `The square of your number is 25.0.`.

Class

python
square_class.py
from tap import tapify

class Squarer:
def __init__(self, num: float) -> None:
"""Initialize the Squarer with a number to square.

:param num: The number to square.
"""
self.num = num

def get_square(self) -> float:
"""Get the square of the number."""
return self.num ** 2

if __name__ == '__main__':
squarer = tapify(Squarer)
print(f'The square of your number is {squarer.get_square()}.')


Running `python square_class.py --num 2` prints `The square of your number is 4.0.`.

Dataclass

python
square_dataclass.py
from dataclasses import dataclass

from tap import tapify

dataclass
class Squarer:
"""Squarer with a number to square.

:param num: The number to square.
"""
num: float

def get_square(self) -> float:
"""Get the square of the number."""
return self.num ** 2

if __name__ == '__main__':
squarer = tapify(Squarer)
print(f'The square of your number is {squarer.get_square()}.')


Running `python square_dataclass.py --num -1` prints `The square of your number is 1.0.`.

Help

The help string on the command line is set based on the docstring for the function or class. For example, running `python square_function.py -h` will print:


usage: square_function.py [-h] --num NUM

Square a number.

options:
-h, --help show this help message and exit
--num NUM (float, required) The number to square.


Note that for classes, if there is a docstring in the `__init__` method, then `tapify` sets the help string description to that docstring. Otherwise, it uses the docstring from the top of the class.

Command line vs explicit arguments

`tapify` can simultaneously use both arguments passed from the command line and arguments passed in explicitly in the `tapify` call. Arguments provided in the `tapify` call override function defaults, and arguments provided via the command line override both arguments provided in the `tapify` call and function defaults. We show an example below.

python
add.py
from tap import tapify

def add(num_1: float, num_2: float = 0.0, num_3: float = 0.0) -> float:
"""Add numbers.

:param num_1: The first number.
:param num_2: The second number.
:param num_3: The third number.
"""
return num_1 + num_2 + num_3

if __name__ == '__main__':
added = tapify(add, num_2=2.2, num_3=4.1)
print(f'The sum of your numbers is {added}.')


Running `python add.py --num_1 1.0 --num_2 0.9` prints `The sum of your numbers is 6.0.`. (Note that `add` took `num_1 = 1.0` and `num_2 = 0.9` from the command line and `num_3=4.1` from the `tapify` call due to the order of precedence.)

Known args

Calling `tapify` with `known_only=True` allows `tapify` to ignore additional arguments from the command line that are not needed for the function or class. If `known_only=False` (the default), then `tapify` will raise an error when additional arguments are provided. We show an example below where `known_only=True` might be useful for running multiple `tapify` calls.

python
person.py
from tap import tapify

def print_name(name: str) -> None:
"""Print a person's name.

:param name: A person's name.
"""
print(f'My name is {name}.')

def print_age(age: int) -> None:
"""Print a person's age.

:param name: A person's age.
"""
print(f'My age is {age}.')

if __name__ == '__main__':
tapify(print_name, known_only=True)
tapify(print_age, known_only=True)


Running `python person.py --name Jesse --age 1` prints `My name is Jesse.` followed by `My age is 1.`. Without `known_only=True`, the `tapify` calls would raise an error due to the extra argument.

Other Changes

https://github.com/swansonk14/typed-argument-parser/pull/76 Add description support for Tap based on the `__doc__` attribute.

https://github.com/swansonk14/typed-argument-parser/pull/81 Fix help text around positional arguments (resolves https://github.com/swansonk14/typed-argument-parser/issues/79).

https://github.com/swansonk14/typed-argument-parser/pull/82 Add README warning about unpickling untrusted data (resolves https://github.com/swansonk14/typed-argument-parser/issues/73).

https://github.com/swansonk14/typed-argument-parser/pull/83 Fix handling of decorated classes (resolves https://github.com/swansonk14/typed-argument-parser/issues/80).

https://github.com/swansonk14/typed-argument-parser/pull/91 Add support for single-quoted documentation (resolves https://github.com/swansonk14/typed-argument-parser/issues/84).

https://github.com/swansonk14/typed-argument-parser/pull/96 Add support for Python 3.11.

1.7.2

Support for Python 3.10 Union Types

This release adds support for the `|` operator in place of `Union` for Python 3.10. For example:

Using the `Union` operator in Python 3.6+

python
from tap import Tap
from typing import Union

def to_number(string: str) -> Union[float, int]:
return float(string) if '.' in string else int(string)

class Args(Tap):
number: Union[float, int]

def configure(self):
self.add_argument('--number', type=to_number)

args = Args().parse_args()

Page 1 of 4

© 2024 Safety CLI Cybersecurity Inc. All Rights Reserved.