ruff icon indicating copy to clipboard operation
ruff copied to clipboard

F401+F811 false positive

Open dalcinl opened this issue 2 years ago • 4 comments
trafficstars

Minimal reproducer

from foo import Foo
from typing import TypeAlias

class Bar:
    Foo: TypeAlias = Foo
    def bar(self) -> Foo: ...

Output

$ ruff stub.pyi 
stub.pyi:1:17: F401 `foo.Foo` imported but unused
stub.pyi:5:5: F811 Redefinition of unused `Foo` from line 1
Found 2 error(s).
1 potentially fixable with the --fix option.

Ruff version: 0.0.227

dalcinl avatar Jan 27 '23 10:01 dalcinl

Confirmed with 0.0.236 with a .pyi file. Doesn't occur with a .py file unless prepending with from __future__ import annotations.

ngnpope avatar Jan 27 '23 11:01 ngnpope

Is this, maybe, the same as #1401?

charliermarsh avatar Jan 27 '23 13:01 charliermarsh

I believe it is not exactly the same. My reproducer would be equivalent to:

from foo import Foo

class Bar:
    Foo = Foo
    def bar(self) -> Foo: ...

and ruff is happy with this code.

dalcinl avatar Jan 27 '23 14:01 dalcinl

This is a small variation to my original reproducer:

from typing import TypeAlias
class Foo: ...

class Bar:
    Foo: TypeAlias = Foo
    def bar(self) -> Foo: ...

This time Ruff is happy with it.

  1. My original reproducer triggers the warnings.
  2. Similar code with a locally defined symbol does not.
  3. Removing the TypeAlias annotation silences the warning.
  4. Changing the annotation to Foo: Type = Foo also silences the warning. So far this looks like a subtle bug related to visibility and/or the TypeAlias annotation.

dalcinl avatar Jan 29 '23 07:01 dalcinl

Yeah this is really tricky.

charliermarsh avatar May 18 '23 16:05 charliermarsh

Obligatory link to Tweet: https://twitter.com/charliermarsh/status/1659233087786459139

charliermarsh avatar May 18 '23 16:05 charliermarsh

I believe we need to change the logic in this case to eagerly resolve if the binding is already defined, and otherwise, go through standard deferred resolution.

charliermarsh avatar May 18 '23 16:05 charliermarsh