Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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 module I have used in my code. This way I could either explicitly import these names or replace the names with module.name. Is there a tool designed to accomplish such a task?

like image 260
Brian Fitzpatrick Avatar asked Dec 25 '22 01:12

Brian Fitzpatrick


1 Answers

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 really.long.module.name
import really.long.module.name as rlmn
from really.long.module.name import obvious_name

really.long.module.name.foo()  # full module name
rlmn.bar()                     # 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.)

like image 179
chepner Avatar answered Dec 26 '22 15:12

chepner