0

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.

4
  • 1
    You should probably use argparse: parser.add_argument('raw-input', action='validate_raw_input'), etc. See this question, please. Commented Aug 29, 2023 at 0:07
  • 1
    Thanks @Andrey. This did work. I'll post an update that shows an exact solution. Thank you! Commented Aug 29, 2023 at 18:42
  • @Andrey I have now updated the code. If you have any ideas on how to better type my code, please let me know. Commented Aug 30, 2023 at 16:07
  • @nonoman657, typing is for static analysis and there are no type aliases in runtime. I suggest you to define an enum AvailableTypes(str, enum.Enum) with properties: my_custom_type, another_type, etc. Forget about typing module for some time. Commented Aug 31, 2023 at 0:37

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.