Is there an IDE/utility to refactor Python * imports to use standard module.member syntax?

前端 未结 2 1680
一个人的身影
一个人的身影 2020-12-14 07:44

I was recently tasked with maintaining a bunch of code that uses from module import * fairly heavily.

This codebase has gotten big enough that import c

2条回答
  •  时光取名叫无心
    2020-12-14 08:22

    Here are the other related tools mentioned:

    • working with AST directly, which is very low-level for your use.
    • working with modulefinder which may have a lot of the boilerplate code you are looking for,
    • rope, a refactoring library (@Lucas Graf),
    • the bicycle repair man, a refactoring libary
    • the logilab-astng library used in pylint

    More about pylint

    pylint is a very good tool built on top of ast that is already able to tell you where in your code there are from somemodule import * statements, as well as telling you which imports are not necessary.

    example:

    # next is what's on line 32
    from re import *
    

    this will complain:

    W: 32,0: Wildcard import re
    W: 32,0: Unused import finditer from wildcard import
    W: 32,0: Unused import LOCALE from wildcard import
    ... # this is a long list ...
    

    Towards a solution?

    Note that in the above output pylint gives you the line numbers. it might be some effort, but a refactoring tool can look at those particular warnings, get the line number, import the module and look at the __all__ list, or using a sandboxed execfile() statement to see the module's global names (would modulefinder help with that? maybe...). With the list of global names from __all__ and the names that pylint complains about, you can have two set() and proceed to get the difference. Replace the line featuring wildcard imports with specific imports.

提交回复
热议问题