I had a little fight with mypy recently. Let's say i have a variable which can be a dict or a list (here self.my_list). Later, in a function (here: get), I want to access a value in this list or dict.
from typing import Union, Any
class my_class:
def __init__(self, whatever: Union[list, dict]):
self.my_list: Union[list, dict] = whatever
def get(self, key: Union[int, str]) -> Any:
return self.my_list[key]
Mypy gaves me the following error for the line where I try to access a value in my_list:
Invalid index type "Union[int, str]" for "Union[List[Any], Dict[Any, Any]]"; expected type "int"
- Someone has any idea how to handle this error ?
- Is it maybe bad from start to have a variable which can be a dict or a list ?