From b42e57420c621c3ff39200d8c72bf115620743f0 Mon Sep 17 00:00:00 2001 From: Tomas R Date: Wed, 3 May 2023 13:16:40 +0200 Subject: [PATCH] Reduce monkeypatching in pyflakes checker (#372) Chipping away at #183 Got rid of the monkeypatched `LAMBDA`. What's changed -> - Default argument values cannot be forward references anymore: ```python def bar(x: type = SomeClass) -> None: ... # F821 undefined name 'SomeClass' class SomeClass: ... ``` I think it makes sense to not allow this anyway - it's similar to what we did with classes previously. --- CHANGELOG.md | 12 ++++++++++++ pyi.py | 11 ----------- tests/forward_refs.pyi | 8 ++++++++ 3 files changed, 20 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 97375ea6..a691652e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # Change Log +## Unreleased + +* The way in which flake8-pyi modifies pyflakes runs has been improved. When + flake8-pyi is installed, pyflakes will now complain about forward references + in default values for function and method parameters (the same as pyflakes + does when it checks `.py` files). Unlike in `.py` files, forward references + in default values are legal in stub files. However, they are never necessary, + and are considered bad style. (Forward references for parameter *annotations* + are still allowed.) + + Contributed by [tomasr8](https://github.com/tomasr8). + ## 23.5.0 * flake8-pyi no longer supports being run with flake8 <5.0.4. diff --git a/pyi.py b/pyi.py index 336c0b35..3110d625 100644 --- a/pyi.py +++ b/pyi.py @@ -216,17 +216,6 @@ def ASSIGN( self.deferHandleNode(tree.value, tree) - def LAMBDA(self, node: ast.Lambda) -> None: - """This is likely very brittle, currently works for pyflakes 1.3.0. - - Deferring annotation handling depends on the fact that during calls - to LAMBDA visiting the function's body is already deferred and the - only eager calls to `handleNode` are for annotations. - """ - self.handleNode, self.deferHandleNode = self.deferHandleNode, self.handleNode # type: ignore[method-assign] - super().LAMBDA(node) - self.handleNode, self.deferHandleNode = self.deferHandleNode, self.handleNode # type: ignore[method-assign] - def handleNodeDelete(self, node: ast.AST) -> None: """Null implementation. diff --git a/tests/forward_refs.pyi b/tests/forward_refs.pyi index 378a1285..142a0a07 100644 --- a/tests/forward_refs.pyi +++ b/tests/forward_refs.pyi @@ -21,3 +21,11 @@ class C: class Outer: class Inner1: ... class Inner2(list[Outer.Inner1]): ... + +# Allow forward references for argument annotations and the return type +def foo(x: SomeClass) -> SomeClass: ... +class SomeClass: ... + +# Disallow forward references for default argument values +def bar(x: type = SomeOtherClass) -> None: ... # Y011 Only simple default values allowed for typed arguments # F821 undefined name 'SomeOtherClass' +class SomeOtherClass: ...