How do unwrap (The problem reminds of rust) a type hint in python? Or in other words how to turn a Variable of type list[Optional[str]]
into list[str]
?
Problem:
I made a litte function to explain my problem.
So i start with a empty list but at a certain point (called Point B here) i want to pass my list to some further Processing in my code. But only if it has values in it. But Pylance
shows me some Error. Even thought i know at this point the list ca not be empty. So do i init a new vaiable? Pylance wants me to wrap the argument of def call_name(a_list:list[Optional[str]]):
also into an Option. But like i said at this point i know there are values in my list, so i do not need the Optional
any longer.
from typing import Optional
from random import randrange
async def test_me():
async def call_name(a_list:list[str]):
'''
This Function is only fired if the list is populated.
'''
for name in a_list:
print(f"Hello, {name}")
some_list:list[Optional[str]] = []
num = randrange(10)
# SOME PROCESSING
if 5 >= num:
# list gets populated
some_list= ["Ricky", "Joe", "Tyrone"]
else:
pass
if len(some_list) > 0:
# POINT B
await call_name(some_list) # <- Type Error
Pylance:
Argument of type "list[str | None]" cannot be assigned to parameter "some_list" of type "list[str]" in function "call_name"
"list[str | None]" is incompatible with "list[str]"
Type parameter "_T@list" is invariant, but "str | None" is not the same as "str"
Consider switching from "list" to "Sequence" which is covariantPylancereportArgumentType
1