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.

nanoman657
  • 39
  • 4
  • 1
    You should probably use argparse: `parser.add_argument('raw-input', action='validate_raw_input')`, etc. See [this question](https://stackoverflow.com/questions/37471636/python-argument-parsing-validation-best-practices), please. – Andrey Aug 29 '23 at 00:07
  • 1
    Thanks @Andrey. This did work. I'll post an update that shows an exact solution. Thank you! – nanoman657 Aug 29 '23 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. – nanoman657 Aug 30 '23 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. – Andrey Aug 31 '23 at 00:37

0 Answers0