agronholm / agronholm/typeguard

Extend `TYPE_CHECKING` handling to classes and assignments

Offen
#456 4 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen
bug
Vorherrschende Sprache
Python
Sterne
1.8k
Forks
145
Ø Merge
8 T. 12 Std.
Gemergte PRs (30 T.)
1

Beschreibung

### Things to check first

- [X] I have searched the existing issues and didn't find my bug already reported there

- [X] I have checked that my bug is still present in the latest release

### Typeguard version

4.2.1

### Python version

3.12.3

### What happened?

`typechecked` code tries to use a class that is hidden behind `TYPE_CHECKING` and should not be required at runtime.

### How can we reproduce the bug?

`bug.py`
```python
# python bug.py && mypy bug.py && pyright bug.py

from __future__ import annotations

from typing import TYPE_CHECKING, TypedDict

# from typeguard import typechecked

if TYPE_CHECKING:

class Args(TypedDict):
x: int
y: int

# @typechecked
def bug() -> None:
args: Args = {"x": 1, "y": 1}
print(args)

bug()
```

`python bug.py && mypy bug.py && pyright bug.py`
```
{'x': 1, 'y': 1}
Success: no issues found in 1 source file
0 errors, 0 warnings, 0 informations
```

Now add the `@typechecked` decorator, and run `python bug.py` again:

```
Traceback (most recent call last):
File "C:\Code\project\bug.py", line 22, in
bug()
File "C:\Code\project\bug.py", line 18, in bug
args: Args = {"x": 1, "y": 1}
^^^^
NameError: name 'Args' is not defined. Did you mean: 'args'?
```

One workaround is to add `bug2.py`:
```python
from typing import TypedDict

class Args(TypedDict):
x: int
y: int
```

and modify `bug.py` to
```python
# python bug.py && mypy bug.py && pyright bug.py

from __future__ import annotations

from typing import TYPE_CHECKING

from typeguard import typechecked

if TYPE_CHECKING:
from bug2 import Args

@typechecked
def bug() -> None:
args: Args = {"x": 1, "y": 1}
print(args)

bug()
```

But that feels kind of unnecessary, I think.

Beitragsleitfaden

Beitragsleitfaden öffnen

Bewertung

Dieses Issue wurde noch nicht bewertet.

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.