agronholm / typeguard

Run-time type checker for Python
Other
1.5k stars 112 forks source link

`check_type([1, "hi"], list[int])` doesn't raise error #439

Closed DanielYang59 closed 6 months ago

DanielYang59 commented 6 months ago

Things to check first

Typeguard version

4.1.5

Python version

3.11.7

What happened?

First time typeguard user and hope I'm not asking a silly question here. But the following code doesn't seem to trigger an error for some reason:

from typeguard import check_type

check_type(value=[1, "hi"], expected_type=list[int])

Maybe I missed something? Thanks.

How can we reproduce the bug?

from typeguard import check_type

check_type(value=[1, "hi"], expected_type=list[int])
davidbrochart commented 6 months ago

See https://github.com/agronholm/typeguard/issues/418#issuecomment-1817515059.

DanielYang59 commented 6 months ago

Thanks for the quick response @davidbrochart . You are legend and that is exactly what I was experiencing. However I tried the following which still didn't got an error for some reason?

import typeguard
from typeguard import check_type, CollectionCheckStrategy

typeguard.config.collection_check_strategy = CollectionCheckStrategy.ALL_ITEMS
check_type(value=[1, "hi"], expected_type=list[int])

Do you have any advice? Thanks!

davidbrochart commented 6 months ago

Seems like a bug.

agronholm commented 6 months ago

Seems like a bug.

No, it's not. check_type() does not use the global configuration. You need to pass the collection_check_strategy=CollectionCheckStrategy.ALL_ITEMS as keyword argument to the function.

This default was adopted because Beartype adopted it, but given how many complaints I've received because of it, typically from users who post bug reports without reading the documentation first, I'm seriously considering reverting this behavior in the next major release.

DanielYang59 commented 6 months ago

typically from users who post bug reports without reading the documentation first

Apologies, I have been one of them 😭 . Yes could confirm this works as expected.

from typeguard import check_type, CollectionCheckStrategy

check_type(
    value=[1, "hi"], expected_type=list[int, int],
    collection_check_strategy=CollectionCheckStrategy.ALL_ITEMS
)