Type hint for a function that returns only a specific set of values

You can do that with literal types. from typing_extensions import Literal # from typing import Literal # Python 3.8 or higher def fun(b: int) -> Literal[“a”, “b”, “c”]: if b == 0: return “a” if b == 1: return “b” return “d” mypy is able to detect the return “d” as a invalid statement: error: … Read more

Python: Typehints for argparse.Namespace objects

Typed argument parser was made for exactly this purpose. It wraps argparse. Your example is implemented as: from tap import Tap class ArgumentParser(Tap): somearg: str parsed = ArgumentParser().parse_args([‘–somearg’, ‘someval’]) the_arg = parsed.somearg Here’s a picture of it in action. It’s on PyPI and can be installed with: pip install typed-argument-parser Full disclosure: I’m one of … Read more

Python >=3.5: Checking type annotation at runtime

I was looking for something similar and found the library typeguard. This can automatically do runtime type checks wherever you want. Checking types directly as in the question is also supported. From the docs, from typeguard import check_type # Raises TypeError if there’s a problem check_type(‘variablename’, [1234], List[int])

Python 3 dictionary with known keys typing

As pointed out by Blckknght, you and Stanislav Ivanov in the comments, you can use NamedTuple: from typing import NamedTuple class NameInfo(NamedTuple): name: str first_letter: str def get_info(name: str) -> NameInfo: return NameInfo(name=name, first_letter=name[0]) Starting from Python 3.8 you can use TypedDict which is more similar to what you want: from typing import TypedDict class … Read more