💡 type-safe args for argparse without much refactoring.
Project description
typed_argparse
💡 type-safe args for argparse without much refactoring.
Motivation
Want to add type annotations to a code base that makes use of argparse
without refactoring all you CLIs?
typed_argparse
allows to do that with minimal changes:
- Add a type
MyArgs(TypedArgs)
that inherits fromTypedArgs
and fill it with type annotations. - Wrap the result of e.g. your
parse_args
function withMyArgs
. - That's it, enjoy IDE auto-completion and strong type safety 😀.
Features
- Implicit runtime validation to ensure type annotations are correct
- Very lightweight
- No dependencies
- Fully typed, no stubs required
Install
$ pip install typed-argparse
The only requirement is a modern Python (3.6+).
Usage
import argparse
import sys
from typing import List, Optional
from typed_argparse import TypedArgs
# Step 1: Add an argument type.
class MyArgs(TypedArgs):
foo: str
num: Optional[int]
files: List[str]
def parse_args(args: List[str] = sys.argv[1:]) -> MyArgs:
parser = argparse.ArgumentParser()
parser.add_argument("--foo", type=str, required=True)
parser.add_argument("--num", type=int)
parser.add_argument("--files", type=str, nargs="*")
# Step 2: Wrap the plain argparser result with your type.
return MyArgs(parser.parse_args(args))
def main() -> None:
args = parse_args(["--foo", "foo", "--num", "42", "--files", "a", "b", "c"])
# Step 3: Done, enjoy IDE auto-completion and strong type safety
assert args.foo == "foo"
assert args.num == 42
assert args.files == ["a", "b", "c"]
if __name__ == "__main__":
main()
Notes:
typed_argparse
validates that no attributes from the type definition are missing, and that no unexpected extra types are present in theargparse.Namespace
object. It also validates the types at runtime. Therefore, if theMyArgs(args)
doesn't throw aTypeError
you can be sure that your type annotation is correct.- If you have usages that require access to the raw
argparse.Namespace
object, you can do so by usingargs.get_raw_args()
. Note that internalargparse.Namespace
object isn't synced with theargs
data itself, i.e., mutating either of them doesn't mutate the other.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
typed_argparse-0.1.5.tar.gz
(9.2 kB
view hashes)
Built Distribution
Close
Hashes for typed_argparse-0.1.5-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 6b66f23c81af9e6fb5a26d51de44d5fada36b4b62053075be40c42da618dd05a |
|
MD5 | ce21be0f13d002078035ccc136c0dee0 |
|
BLAKE2b-256 | aa43e41f30622074ecde30d5175ae55184b1397c0f63f04c553082f1b4c1aee8 |