autoflake icon indicating copy to clipboard operation
autoflake copied to clipboard

incorrectly removes unused variable when surrounded in typing

Open mathematicalcoffee opened this issue 5 years ago • 4 comments

Running autoflake --remove-all-unused-imports on this file

from typing import List, TYPE_CHECKING

if TYPE_CHECKING:
    from pandas import DataFrame

def foo(a: List["DataFrame"]) -> None:
    print(a[0].size)

produces

from typing import List, TYPE_CHECKING

if TYPE_CHECKING:
    pass # <----

def foo(a: List["DataFrame"]) -> None:
    print(a[0].size)

i.e. it removes the DataFrame import despite the type being used. I think this is because it is enclosed in the List because if I include "DataFrame" as a top-level type, the import is retained, as expected:

# this example stays the same
from typing import List, TYPE_CHECKING

if TYPE_CHECKING:
    from pandas import DataFrame

def foo(a: "DataFrame") -> None:
    print(a.size)

mathematicalcoffee avatar Aug 26 '20 01:08 mathematicalcoffee

A temporary workaround for this is to add a line such as:

if TYPE_CHECKING:
    from pandas import DataFrame
    DataFrame  # Prevent autoflake from removing imports.  pylint: disable=pointless-statement

But I hope that this will eventually be fixed as such lines are ugly. :smile:

NeilGirdhar avatar Jan 04 '21 00:01 NeilGirdhar

I just add a # noqa on the import line so it doesn't get removed, easier than the no-op DataFrame you have. But of course then if you later remove the typing that refers to DataFrame, autoflake won't clean it up for you automatically.

mathematicalcoffee avatar Jan 04 '21 01:01 mathematicalcoffee

Ah, thanks. Didn't realize that noqa prevented autoflake.

NeilGirdhar avatar Jan 04 '21 01:01 NeilGirdhar