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.
module.py
ofimport random;if random.random() > 0.5: x = 1
.from module import *
with a list of explicit imports (from module import x, y, z
) and that way you could tell what you missed when name errors pop up (or even better, you could use something likepyflakes
to do static code analysis and tell that for you). As soon as you removefrom module import *
statements, it should be able to tell you what isn't defined.x, y, z
? If it's a nice module or package, it defines__all__
, which makes this very easy. But what if not? Import the module an look at its globals? Meh. That won't work if you want to do a purely static analysis (which one should in my opinion). You'd probably have to build an AST and parse it.old_globals = dict(globals()); from module import *; print [k for k,v in dict(globals()).items() if k not in old_globals or old_globals[k] != v]
, though this requires actually loading the module. So that could at least let you convert a line likefrom numpy import *
tofrom numpy import x,y,z