agronholm / agronholm/typeguard

Check annotated locals bound by `for` and `with` targets

未關閉
#586 4 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視
enhancement
主要語言
Python
星號
1.8k
分支
146
平均合併
8 天 12 小時
30 天內合併 PR
1

描述

Reframed as a feature request, per agronholm's comment below. Originally filed as a bug report.

Typeguard checks the value assigned to an annotated local by `=`, by the walrus operator, by chained assignment and by tuple unpacking. It does not check a value bound to the same annotated name by a `for` target or a `with ... as` target. Same for `async for`, `async with ... as`, `except ... as`, `except* ... as`, a `match` capture pattern and `import ... as`.

The request is to extend the local-variable check to those binding forms, or to whichever subset is worth the transformer complexity. `for` and `with` are the two that turn up in ordinary code.

Same behaviour on 4.6.0 and on main at `123f1abc7e82bbe980c779005de858533e1786c3`, python 3.11.16 / 3.12.14 / 3.13.15. `install_import_hook` behaves like `@typechecked` here, so it is not specific to the decorator. mypy flags all three cases below as `Incompatible types in assignment`.

```python
import io

from typeguard import TypeCheckError, typechecked

@typechecked
def plain_assign() -> None:
x: int
x = "not an int"

@typechecked
def for_target() -> None:
x: int
for x in ["not an int"]:
pass

@typechecked
def with_target() -> None:
x: io.BytesIO
with io.StringIO() as x:
pass

for func in (plain_assign, for_target, with_target):
try:
func()
print(f"{func.__name__}: no error")
except TypeCheckError as exc:
print(f"{func.__name__}: TypeCheckError: {exc}")
```

```
plain_assign: TypeCheckError: value assigned to x (str) is not an instance of int
for_target: no error
with_target: no error
```

貢獻指南

開啟貢獻指南

研究方向

Start by running the issue's @typechecked examples and tracing how annotated local assignments are transformed. Compare the existing plain-assignment check with for and with targets, then determine which binding forms are in scope. Done means supported targets raise TypeCheckError for incompatible values, with tests covering the chosen subset.

由索引模型根據 Issue 內容生成。

評估

技術堆疊
python
領域
devtools
Issue 類型
功能
難度
4/5
預估耗時
3-5 天
活躍度
活躍
描述清晰度
基本清楚
新手友好度
48/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。