mypy question

Thomas Passin list1 at tompassin.net
Sat Dec 30 09:14:05 EST 2023


On 12/29/2023 10:02 AM, Karsten Hilbert via Python-list wrote:
> I agree that mypy's grasp of my intent from
> 
> 	queries:list[dict[str, str | list | dict[str, Any]]]=None,
> 
> into
> 
> 	"List[Dict[str, Union[str, List[Any], Dict[str, Any]]]]"
> 
> seems accurate. I just don't understand why list[dict[str,
> str]] should not pass that construct.

I made a tiny test program with your type signature, and got this error 
message from mypy:

c:\temp\python\typing_test.py:3: error: X | Y syntax for unions requires 
Python 3.10  [syntax]

Aside from that, this variation causes no mypy error (you must use 
Sequence instead of List), and is also more clear about what you are 
trying to get:

from typing import Union, Sequence, Dict

DictType1 = Dict[str, str]
DictType2 = Dict[str, Sequence]
DictType3 = Dict[str, Dict]
QueryType = Sequence[Union[DictType1, DictType2, DictType3]]

def test_typing(queries:QueryType=None):
     print(type(queries))

d1 = {'k1': 'v1', 'k2': 'v2'}
queries = [d1,]
test_typing(queries)

I'm not sure if this captures exactly what you want, but it avoids the 
problem where mypy does not regard str and Union[str, list] as 
equivalent types.  I tested this using Python 3.12.





More information about the Python-list mailing list