lyz-code / autoimport

Autoimport automatically fixes wrong import statements.
https://lyz-code.github.io/autoimport
GNU General Public License v3.0
97 stars 24 forks source link

[Bug] handling top-level `if TYPE_CHECKING: ...` block #231

Closed Jasha10 closed 1 year ago

Jasha10 commented 1 year ago

Description

autoimport does not properly handle top-level use of if TYPE_CHECKING: ...

Steps to reproduce

Case 1:

Run autoimport on the following file:

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    foo = "bar"

The output looks like this:

if TYPE_CHECKING:
    foo = "bar"

Why did the from typing ... import disappear?

Case 2:

Run autoimport on the following file:

if TYPE_CHECKING:
    foo = "bar"

The output looks like this:

from typing import TYPE_CHECKING

Why did the if TYPE_CHECKING: ... block disappear?

Case 3 (this is expected behavior):

Run autoimport on the following file:

from typing import TYPE_CHECKING

The output is empty:

Current behavior

Repeatedly running autoimport on the file from Case 1 causes the file's contents to completely disappear.

Desired behavior

autoimport should not remove the if TYPE_CHECKING: ... block or the related import from typing ....

Environment

 $ python -c "import autoimport.version; print(autoimport.version.version_info())"
------------------------------------------------------------------
     autoimport: 1.3.1
     Python: 3.9.12
     Platform: Linux-5.15.0-52-generic-x86_64-with-glibc2.31
------------------------------------------------------------------
lyz-code commented 1 year ago

I can reproduce the issue, weird, it doesn't happen in 1.2.3 nor in 1.3.0, the bug appeared in 1.3.1 and I have to investigate why did the tests miss this bug.

Thanks for pointing it out. Please until it's fixed use 1.3.0

lyz-code commented 1 year ago

Please @Jasha10 try with 1.3.2, and sorry for the inconveniences :(

Jasha10 commented 1 year ago

No problem! It's working well now -- thanks!!