Tool to help eliminate wildcard imports Tool to help eliminate wildcard imports python python

Tool to help eliminate wildcard imports


NB: pylint does not recommend a set of used imports. When changing this, you have to be aware of other modules importing the code you are modifying, which could use symbols which belong to the namespace of the module you are refactoring only because you have unused imports.

I recommend the following procedure to refactor from foo import *:

  • in an interactive shell, type:

    import reimport foo as module # XXX use the correct module name here!module_name = module.__name__import_line = 'from %s import (%%s)' % module_namelength = len(import_line) - 3print import_line % (',\n' + length * ' ').join([a for a in dir(module)                                                                if not re.match('__.*[^_]{2}', a)])
  • replace the from foo import * line with the one printed above

  • run pylint, and remove the unused imports flagged by pylint
  • run pylint again on the whole code based, looking for imports of non existing sympols
  • run your unit tests

repeat with from bar import *


Here's dewildcard, a very simple tool based on Alex's initial ideas:

https://github.com/quentinsf/dewildcard


This is an old question, but I wrote something that does this based on autoflake.

See here: https://github.com/fake-name/autoflake/blob/master/autostar.py

It works the opposite way dewildcard does, in that it attempts to fully qualify all uses of wildcard items.

E.g.

from os.path import *

Is converted to

import os.path

and all uses of os.path.<func> are prepended with the proper function.