Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# Change Log

## Unreleased

* **Breaking change:** Previously, flake8-pyi monkey patched flake8's F821
(undefined name) check to avoid false positives in stub files. This monkey
patch has been removed, and we recommend to disable F821 when running flake8
on stub files.
* Remove the now unnecessary `--no-pyi-aware-file-checker` option.

## 5.5.0

New error codes:
Expand Down
102 changes: 1 addition & 101 deletions flake8_pyi/checker.py
Original file line number Diff line number Diff line change
@@ -1,106 +1,18 @@
from __future__ import annotations

import argparse
import ast
import logging
import re
from dataclasses import dataclass
from typing import Any, ClassVar, Iterator, Literal
from typing import ClassVar, Iterator

from flake8 import checker
from flake8.options.manager import OptionManager
from flake8.plugins.finder import LoadedPlugin
from flake8.plugins.pyflakes import FlakesChecker
from pyflakes.checker import ModuleScope

from . import errors, visitor

LOG = logging.getLogger("flake8.pyi")


class PyflakesPreProcessor(ast.NodeTransformer):
"""Transform AST prior to passing it to pyflakes.

This reduces false positives on recursive class definitions.
"""

def visit_ClassDef(self, node: ast.ClassDef) -> ast.ClassDef:
self.generic_visit(node)
node.bases = [
# Remove the subscript to prevent F821 errors from being emitted
# for (valid) recursive definitions: Foo[Bar] --> Foo
base.value if isinstance(base, ast.Subscript) else base
for base in node.bases
]
return node


class PyiAwareFlakesChecker(FlakesChecker):
def __init__(self, tree: ast.AST, *args: Any, **kwargs: Any) -> None:
super().__init__(PyflakesPreProcessor().visit(tree), *args, **kwargs)

@property
def annotationsFutureEnabled(self) -> Literal[True]:
"""Always allow forward references in `.pyi` files.

Pyflakes can already handle forward refs for annotations,
but only via `from __future__ import annotations`.
In a stub file, `from __future__ import annotations` is unnecessary,
so we pretend to pyflakes that it's always present when linting a `.pyi` file.
"""
return True

@annotationsFutureEnabled.setter
def annotationsFutureEnabled(self, value: bool) -> None:
"""Does nothing, as we always want this property to be `True`."""

def ASSIGN(
self, tree: ast.Assign, omit: str | tuple[str, ...] | None = None
) -> None:
"""Defer evaluation of assignments in the module scope.

This is a custom implementation of ASSIGN, originally derived from
handleChildren() in pyflakes 1.3.0.

This reduces false positives for:
- TypeVars bound or constrained to forward references
- Assignments to forward references that are not explicitly
demarcated as type aliases.
"""
if not isinstance(self.scope, ModuleScope):
super().ASSIGN(tree)
return

for target in tree.targets:
self.handleNode(target, tree)

self.deferFunction(lambda: self.handleNode(tree.value, tree))

def handleNodeDelete(self, node: ast.AST) -> None:
"""Null implementation.

Lets users use `del` in stubs to denote private names.
"""
return


class PyiAwareFileChecker(checker.FileChecker):
def run_check(self, plugin: LoadedPlugin, **kwargs: Any) -> Any:
if plugin.obj is FlakesChecker:
if self.filename == "-":
filename = self.options.stdin_display_name
else:
filename = self.filename

if filename.endswith(".pyi"):
LOG.info(
f"Replacing FlakesChecker with PyiAwareFlakesChecker while "
f"checking {filename!r}"
)
plugin = plugin._replace(obj=PyiAwareFlakesChecker)
return super().run_check(plugin, **kwargs)


_TYPE_COMMENT_REGEX = re.compile(r"#\s*type:\s*(?!\s?ignore)([^#]+)(\s*#.*?)?$")


Expand Down Expand Up @@ -139,15 +51,3 @@ def add_options(parser: OptionManager) -> None:
"""This is brittle, there's multiple levels of caching of defaults."""
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I sort of worry that nobody on the current maintainers team knows what this cryptic comment is actually referring to ¯\_(ツ)_/¯

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

... and it's gone.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Unless @ambv remembers what he meant with that comment. It's only been 10 years, after all.)

parser.parser.set_defaults(filename="*.py,*.pyi")
parser.extend_default_ignore(errors.DISABLED_BY_DEFAULT)
parser.add_option(
"--no-pyi-aware-file-checker",
default=False,
action="store_true",
parse_from_config=True,
help="don't patch flake8 with .pyi-aware file checker",
)

@staticmethod
def parse_options(options: argparse.Namespace) -> None:
if not options.no_pyi_aware_file_checker:
checker.FileChecker = PyiAwareFileChecker
2 changes: 1 addition & 1 deletion tests/classdefs.pyi
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# flags: --extend-ignore=Y023
# flags: --extend-ignore=F821,Y023

import abc
import builtins
Expand Down
2 changes: 1 addition & 1 deletion tests/del.pyi
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# flags: --extend-ignore=Y037
# flags: --extend-ignore=F821,Y037
from typing import TypeAlias, Union

ManyStr: TypeAlias = list[EitherStr]
Expand Down
40 changes: 0 additions & 40 deletions tests/forward_refs.pyi

This file was deleted.

56 changes: 0 additions & 56 deletions tests/forward_refs_annassign.pyi

This file was deleted.

1 change: 0 additions & 1 deletion tests/pep695_py312.pyi
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# Temporary workaround until pyflakes supports PEP 695:
# flags: --extend-ignore=F821

import typing
Expand Down
2 changes: 1 addition & 1 deletion tests/typevar.pyi
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# flags: --extend-ignore=Y037
# flags: --extend-ignore=F821,Y037
import typing
from typing import Annotated, ParamSpec, TypeVar, TypeVarTuple, Union

Expand Down
10 changes: 0 additions & 10 deletions tests/vanilla_flake8_not_clean_forward_refs.pyi

This file was deleted.