How can I check for unused import in many Python files?

后端 未结 11 2109
名媛妹妹
名媛妹妹 2020-12-13 01:58

I remember when I was developing in C++ or Java, the compiler usually complains for unused methods, functions or imports. In my Django project, I have a bunch of Python fil

相关标签:
11条回答
  • 2020-12-13 02:25

    If you use the eclipse IDE with pydev and mylyn, it provides automatic checking and highlighting for unused imports, among other things. It integrates with pylint as well.

    0 讨论(0)
  • 2020-12-13 02:28

    PyFlakes (similar to Lint) will give you this information.

    pyflakes python_archive.py
    
    Example output:
    python_archive.py:1: 'python_archive2.SomeClass' imported but unused
    
    0 讨论(0)
  • 2020-12-13 02:32

    I use flake8 to check the style, and then isort+autoflake to auto remove the unused imports.

    Check: See more at flake8 vs pyflake

    pip install flake8 --user
    flake8 .
    

    Reformat: see more at why isort+autoflake

    pip install isort autoflake --user
    isort -rc -sl .
    autoflake --remove-all-unused-imports -i -r .
    isort -rc -m 3 .
    
    0 讨论(0)
  • 2020-12-13 02:32

    As of 2020, vulture is recommended.

    Installation

    pip install vulture  # from PyPI
    

    Usage

    vulture myscript.py
    

    For all python files under your project.

    find . -name "*.py" | xargs vulture | grep "unused import"
    

    Example

    Applies to the code below.

    import numpy as np
    import pandas as pd
    
    df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
    

    The results are as follows.

    ➜ vulture myscript.py
    myscript.py:1: unused import 'np' (90% confidence)
    myscript.py:4: unused variable 'df' (60% confidence)
    
    0 讨论(0)
  • 2020-12-13 02:35

    I have been using pyflakes successfully and wished to auto-remove the unused imports.

    I recently found autoflake:

    • Uses pyflakes for checking.
    • Defaults to removing unused standard library imports and redundant pass statements.
    • Has options for removing other unused imports and unused variables.
    0 讨论(0)
提交回复
热议问题