agronholm / typeguard

Run-time type checker for Python
Other
1.52k stars 114 forks source link

check_type() on nested list of TypedDict doesn't check all elements of list #417

Closed devinnasar closed 11 months ago

devinnasar commented 11 months ago

Things to check first

Typeguard version

4.1.5

Python version

3.11

What happened?

I'm attempting to force validation on my function arguments, one of which is itself a list of dicts with known keys. Typeguard only seems to be performing type validation on the first element of the list of dicts. I'm stumped as to why this is happening.

from typing import TypedDict, Unpack, Required, NotRequired, List
from typeguard import check_type

class entitySearch_tag_param_type(TypedDict):
    key: str
    value: str

class entitySearch_query_param_types(TypedDict, total=False):
    alertSeverity: str
    domain: str 
    name: str 
    tags: List[entitySearch_tag_param_type]
    type: str 

class myClass():
    # inits etc ...
    def construct_entitySearch_querystring(self, **kwargs):
        print(kwargs)
        check_type(kwargs, entitySearch_query_param_types)

def main():

    # tagsDict = [{'key':"12",'value':'y'}] # passes

    # tagsDict = [{'snarfblat':'x', 'dinglehopper':'y'}] # fails with:
    # File "/Users/devin.nasar/project/.venv/lib/python3.11/site-packages/typeguard/_checkers.py", line 256, in check_typed_dict
    #     raise TypeCheckError(f"has unexpected extra key(s): {keys_formatted}")
    # typeguard.TypeCheckError: item 0 of value of key 'tags' of dict has unexpected extra key(s): "dinglehopper", "snarfblat"

    tagsDict=[ # passes again, what gives?
        {'key':"12",'value':'y'}, # valid
        {'snarfblat':'x', 'dinglehopper':'y'}, # invalid keys, should raise
        {'bangarang':1, 'blargh':'x'}, # invalid values, should raise
        "teststring" # not a dict, should raise
    ]

    myClass.construct_entitySearch_querystring(
        alertSeverity="12",
        tags=tagsDict
    )

if __name__ == "__main__":
    main()

How can we reproduce the bug?

Run the code in the bug report.

agronholm commented 11 months ago

This is not a bug, it's a configuration setting. Set typeguard.config.collection_check_strategy = CollectionCheckStrategy.ALL_ITEMS and you're golden.