For example, if my code were to be like this in Python 3.10 :
from typing import Union
class TupleInvalid(Exception):
pass
TestValue = Union[int, str, float]
TestListA = tuple[str, TestValue]
TestListB = tuple[str, TestValue, TestValue]
def two_or_three(*tuples: TestListA | TestListB) -> str:
for x in tuples:
if isinstance(x[0], str):
if len(x) == 2:
return 'two'
elif len(x) == 3:
return 'three'
else:
raise TupleInvalid('Tuple should be 2 or 3 long')
else:
raise TupleInvalid(
'Tuple should be (<str>, <int | float | str>, \
<int | float | str> (optional)')
print(two_or_three(("test", 3, 4.5)))
print(two_or_three(("testing", 'hi')))
My linter would be able to pick up on the fact the argument *tuples
should be a tuple consisting of either tuple[str, TestValue]
or tuple[str, TestValue, TestValue]
. In Python 3.9 however, it doesn't seem to be able to work. I tried making it an Union[TestListA, TestListB]
but that just gives a lot of errors. ( TypeError: Cannot instantiate typing.Union)
Using or
does not give any errors but my linter doesn't seem to be able to find the possible second type then.
(*tuples: TestListA or TestListB)
Python 3.9 doesn't have that feature. It is introduced in Python 3.10.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.