Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tool to help eliminate wildcard imports

Tags:

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.

like image 408
Paul Avatar asked Aug 30 '11 20:08

Paul


People also ask

How do I get rid of wildcard imports?

Disable wildcard importsIn the Settings/Preferences dialog ( Ctrl+Alt+S ), select Editor | Code Style | Java | Imports. Make sure that the Use single class import option is enabled.

Are wildcard imports bad Java?

Using wildcard imports in Java would not affect runtime performance of a Java program at all, but compile-time performance may be affected a little.

How do I stop star imports in IntelliJ?

To avoid IntelliJ IDEA replacing imports with * , you need to configure the Class count to use import with '*' and Names count to use static import with '*' preferences: Go to Preferences > Editor > Code Style > Java.


1 Answers

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 *

like image 148
gurney alex Avatar answered Sep 18 '22 15:09

gurney alex