On 12/30/2023 9:14 AM, Thomas Passin via Python-list wrote:
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.

In doing more testing, I have learned that my suggestion above does work, *except* that you cannot mix-and-match different DictTypex types within the same Sequence - meaning within the same query argument. Any of the Union types is OK but they all have to be the same in any instance.

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to