Unimport can understand that imports are used these cases.
from typing import List, Dict
def test(arg: List[Dict]) -> None:
passUnimport supports the following cases
from typing import List, Dict
def test(arg: 'List[Dict]') -> None:
passfrom typing import List, Dict
def test(arg: "List['Dict']") -> None:
passImports in the example below aren't flag as unused by unimport.
from typing import Any
from typing import Tuple
from typing import Union
def function(a, b):
# type: (Any, str) -> Union[Tuple[None, None], Tuple[str, str]]
passFor more information
PEP 526 - Syntax for Variable Annotations
Unimport looks at the items in the __all__ list, if it matches the imports, marks it
as being used.
import os
__all__ = ["os"] # this import is used and umimport can understandOther supported operations, append and extend
from os import *
__all__ = []
__all__.append("removedirs")
__all__.extend(["walk"])after refactoring
from os import removedirs, walk
__all__ = []
__all__.append("removedirs")
__all__.extend(["walk"])When used with --include-star-import, unimport can refactor star imports into explicit
imports by detecting which names are actually used in the code.
input
from os import *
from json import *
print(getcwd())
print(JSONEncoder)output
from os import getcwd
from json import JSONEncoder
print(getcwd())
print(JSONEncoder)When multiple star imports export the same name, unimport deduplicates suggestions so that only the last import provides each name (matching Python's shadowing semantics). This produces correct output in a single pass.
input
from _collections import *
from collections import *
print(defaultdict)output
from collections import defaultdict
print(defaultdict)If the star imports partially overlap, each import keeps only its unique names:
input
from collections import *
from _collections import *
print(Counter)
print(defaultdict)output
from collections import Counter
from _collections import defaultdict
print(Counter)
print(defaultdict)Star import suggestions also respect explicit imports — if a name already has an explicit import, star imports won't produce a duplicate for that name.
Unimport tries to better understand whether the import is unused by performing scope analysis.
Let me give a few examples.
input
import x
def func():
import x
def inner():
import x
xoutput
def func():
def inner():
import x
xinput
import x
class Klass:
def f(self):
import x
def ff():
import x
xoutput
class Klass:
def f(self):
def ff():
import x
x