I have some python code like the below. How do I properly check the input to ensure that it is of my custom typealias to comply with mypy? I currently get a "error: Incompatible types in assignment" error.
from typing import TypeAlias, Literal, Union
from sys import argv
CustomType: TypeAlias = Literal['MyCustomType']
raw_input: Union[CustomType, str] = argv[1]
default_value: CustomType = 'MyCustomType'
typed_input: CustomType = raw_input if type(raw_input) == CustomType else default_value
Edit: In line with @Andrey's suggestion, I have now done the following:
from argparse import ArgumentParser, Namespace
from typing import TypeAlias, Literal, Union, get_args
from sys import argv
CustomType: TypeAlias = Literal['MyCustomType']
raw_input: Union[CustomType, str] = argv[1]
default_value: CustomType = 'MyCustomType'
typed_input: CustomType = raw_input if type(raw_input) == CustomType else default_value
parser: ArgumentParser = ArgumentParser(description="Processes your arguments")
parser.add_argument("argument", choices=get_args(CustomType))
arguments: Namespace = parser.parse_args()
my_argument: CustomType = arguments.argument # This can be typed however you want
Regrettably, the last line doesn't have the level of typing that I would prefer. I would prefer something like
parser.add_argument("argument", type=CustomType, choices=get_args(CustomType))
but I do not know that it is permitted in Python. At any rate, it is certain that the values of myargument
will be of the CustomType options. I just wish this solution was a bit more elegant. If anyone has ideas, I'm open to them.