agronholm / typeguard

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

Bring back `argname` or help to figure out the way to do the same. #438

Open rtb-zla-karma opened 6 months ago

rtb-zla-karma commented 6 months ago

Things to check first

Feature description

I've wanted to update typeguard dependency in project from version 2.13.3 to latest, which is 4.1.5. Coincidently previous version had exactly what we needed which is type checking + custom message on error but since 3.0.0 it was dropped.

Is there any workaround that I'm not aware of? Will you consider to bring that feature back?

Use case

We have test which goes roughly like this:

from typing import List
from typeguard import check_type

# run using `pytest` with `typeguard==2.13.3`
def test_request_for_data():
    test_id = "553834731"
    expected_data_types = {
        "key1": ["foo", "bar"],
        "key2": [],
        "key3": str,
        "key4": "value1",
        "key5": False,
        "key6": List[str],
    }
    # data = _request_for_data([test_id])[0]  # original
    data = {"key1": ["foo", "bar"], "key2": [], "key3": True, "key4": "value1", "key5": False, "key6": ["hi", "hello"]}  # failing data example
    assert len(data) == len(expected_data_types)
    for key, value in expected_data_types.items():
        if isinstance(value, (int, float, str, list)):
            assert data[key] == value
        else:
            check_type(f"returned {key} value", data[key], value)

We check for exact value or data type match defined by either regular types like str or using types from typing module.

Old error message: TypeError: type of returned key3 value must be str; got bool instead New error message (without 1st argument): typeguard.TypeCheckError: bool is not an instance of str

As you can see in our case old message allowed us to know instantly for which key the value was incorrect but in new version there is no way to customize it.