Brian Fitzpatrick Brian Fitzpatrick - 1 year ago 78
Python Question

Is there a tool to check what names I have used from a "wildly" imported module?

I've been using python to do computations for my research. In an effort to clean up my terrible code, I've been reading Code Like a Pythonista: Idiomatic Python by David Goodger.

In this article, Goodger advises against "wild-card" imports of the form

from module import *

My code uses a lot of these. I'd like to clean my code up, but I'm not sure how. I'm curious if there is a way to check what names from
I have used in my code. This way I could either explicitly import these names or replace the names with
. Is there a tool designed to accomplish such a task?

Answer Source

Use a tool like pyflakes (which you should use anyway) to note which names in your code become undefined after you replace from module import * with import module. Once you've positively identified every instance of a name imported from module, you can assess whether to

  1. Always use import module and module.x for x imported from module.
  2. Use import module as m and m.x if the module name is long.
  3. Selectively import some names from module into the module namespace with from module import x, y, z

The above three are not mutually exclusive; as an extreme example, you can use all three in the same module:

import as rlmn
from import obvious_name  # full module name                     # module alias
obvious_name()                 # imported name

all in the same code. (I don't recommend using all three in the same module. Stick with either the full module name or the alias throughout a single module, but there is no harm importing common, obvious names directly and using the fully qualified name for more obscure module attributes.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download