agronholm / typeguard

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

`*args` with forward ref not working with pytest #474

Open manulera opened 1 month ago

manulera commented 1 month ago

Things to check first

Typeguard version

4.3.0

Python version

3.11.7

What happened?

First of all, thanks for the great library, I think it's a great idea and I am hoping to implement it in a library that I maintain.

Below is a minimal module that causes the error:

example.py: the module file

from typing import List

class OtherClass:
    def __init__(self, *args: List["ForwardRef"], **kwargs: str) -> None:
        args[0][0].name  # < this is correctly typed in the IDE
        pass

class ForwardRef:
    def __init__(self, name):
        self.name = name

if __name__ == "__main__":
    my_forward_ref = ForwardRef("name")
    other_class = OtherClass([my_forward_ref])

test_example.py: the test file (just contains an import statement)

import example

We run a test like this

pytest -v --typeguard-packages=:all: test_example.py

The error is:

test_dummy.py:1: in <module>
    import example
<frozen importlib._bootstrap>:1176: in _find_and_load
    ???
<frozen importlib._bootstrap>:1147: in _find_and_load_unlocked
    ???
<frozen importlib._bootstrap>:690: in _load_unlocked
    ???
.venv/lib/python3.11/site-packages/typeguard/_importhook.py:98: in exec_module
    super().exec_module(module)
example.py:5: in <module>
    class OtherClass:
example.py:7: in OtherClass
    def __init__(self, *args: List["ForwardRef"], **kwargs: str) -> None:
E   NameError: name 'ForwardRef' is not defined
============= short test summary info =========
ERROR test_dummy.py - NameError: name 'ForwardRef' is not defined

There is no problem when using these functions normally, even if adding the typechecked decorator.

How can we reproduce the bug?

The files example.py and test_example.py (attached are sufficient to reproduce the above example).

reproduce_error.zip