22

I'm refactoring and eliminating wildcard imports on some fairly monolithic code.

Pylint seems to do a great job of listing all the unused imports that come along with a wildcard import, but what i wish it did was provide a list of used imports so I can quickly replace the wildcard import. Any quick ways of doing this? I'm about to go parse the output of pyLint and do a set.difference() on this and the dir() of the imported module. But I bet there's some tool/procedure I'm not aware of.

Paul
  • 2,973
  • 6
  • 31
  • 40
  • 1
    Have you tried looking for an `__all__` – Jakob Bowyer Aug 30 '11 at 20:43
  • Great question! I wish there were something like this. pyflakes could probably be modified to attempt to ignore a wildcard line and reparse, generating a list of now-undefined names. I don't know of any tool that currently does this automatically though. :c – Corbin Aug 30 '11 at 20:58
  • 1
    When using PyDev with Eclipse, it shows unused imports (even if imported with wildcards) – JBernardo Aug 30 '11 at 21:04
  • 1
    How about just removing the wildcard import, and importing all the modules that are now underlined with squiggly red lines? – inspectorG4dget Aug 30 '11 at 21:47

3 Answers3

8

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 re
    import foo as module # XXX use the correct module name here!
    
    module_name = module.__name__
    import_line = 'from %s import (%%s)' % module_name
    length = len(import_line) - 3
    print 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 *

gurney alex
  • 13,247
  • 4
  • 43
  • 57
5

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

https://github.com/quentinsf/dewildcard

0

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.

Fake Name
  • 5,556
  • 5
  • 44
  • 66