Search code examples
pythonsyntaxiderefactoringreadability

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


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 conflicts/naming ambiguity/"where the heck did this function come from, there are like eight imported modules that have one with the same name?!"ism have become more and more common.

Moving forward, I've been using explicit members (i.e. import module ... module.object.function() to make the maintenance work I do more readable.

But I was wondering: is there an IDE or utility which robustly parses Python code and refactors * import statements into module import statements, and then prepends the full module path onto all references to members of that module?

We're not using metaprogramming/reflection/inspect/monkeypatching heavily, so if aforementened IDE/util behaves poorly with such things, that is OK.


Solution

  • Not a perfect solution, but what I usually do is this:

    1. Open Pydev
    2. Remove all * imports
    3. Use the optimize imports command (ctrl+shift+o) to re-add all the imports

    Roughly solves the problem :)


    If you want to build a solution yourself, try http://docs.python.org/library/modulefinder.html