I'm trying to use a match/case instruction to process things differently based on type:
Code looks like:
def checkArg(arg: str | list[str]) -> str:
match arg:
case str():
return 'str'
case list():
return 'list(str)'
case _:
return "unmatched"
def test(arg: str | list[str]):
print(f'{arg=!r}: {checkArg(arg)}')
test(0)
test('This should match')
test(['This', 'should', 'match'])
test(['This', 'should', 0, 'not', 'match'])
- As expected type hinting makes PyCharm flag
test(0)
- But I don't get any warning for
test(['This', 'should', 0, 'not', 'match'])
so I could be missing something already - I can't find what I could use instead of
case list()
to reject the 4th test and restrict the match to proper list of strings (I tried things likecase list[str]()
but either the syntax is not valid or that doesn't work).
I'm trying to use a match/case instruction to process things differently based on type:
Code looks like:
def checkArg(arg: str | list[str]) -> str:
match arg:
case str():
return 'str'
case list():
return 'list(str)'
case _:
return "unmatched"
def test(arg: str | list[str]):
print(f'{arg=!r}: {checkArg(arg)}')
test(0)
test('This should match')
test(['This', 'should', 'match'])
test(['This', 'should', 0, 'not', 'match'])
- As expected type hinting makes PyCharm flag
test(0)
- But I don't get any warning for
test(['This', 'should', 0, 'not', 'match'])
so I could be missing something already - I can't find what I could use instead of
case list()
to reject the 4th test and restrict the match to proper list of strings (I tried things likecase list[str]()
but either the syntax is not valid or that doesn't work).
1 Answer
Reset to default 0You can add a condition that validates all items as instances of str
:
def checkArg(arg: str| list[str]) -> str:
match arg:
case str():
return 'str'
case [*items] if all(isinstance(item, str) for item in items):
return 'list(str)'
case _:
return "unmatched"
Demo: https://ideone/pHVPRI
Argument of type "list[str | int]" cannot be assigned to parameter "arg" of type "str | list[str]" in function "test"
– matszwecja Commented Mar 21 at 10:11test(['This', 'should', 0, 'not', 'match'])
so I guess this is a problem in your PyCharm setup (Mypy playground) – mkrieger1 Commented Mar 21 at 10:18