2

Suppose I read code written by someone else where "from import *" is used, how can I determine what module a function is from? Is this the reason why some people frown upon "from import *"?

talloaktrees
  • 3,508
  • 6
  • 28
  • 43
  • This may be a good answer: http://stackoverflow.com/a/3615206/770830 – bereal Mar 06 '12 at 11:16
  • go into a python shell, run the (admittedly bad-style) import *, then do str(function) - this will tell you which module it's coming from... then replace with proper imports ;) – Hoff Mar 06 '12 at 11:28
  • I just did this.. it doesn't seem to do what you say. – talloaktrees Mar 06 '12 at 12:49
  • 1
    `str` won't do the trick. What you can do is look at the `__module__` of each function, e.g. `from urllib2 import urlopen; urlopen.__module__` → `'urllib2'`. – Fred Foo Mar 06 '12 at 13:24

2 Answers2

5

Yes, this is why from <module> import * is considered bad style. What you can do is remove these * imports one by one, then check which NameErrors you get and solve them one by one by explicit imports.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • 2
    Good idea. This falls down of course if the `from import *` happens to overwrite some object's name in the local namespace. Then you'd get all possible kinds of errors after removing the `import` statement. Which is yet another reason not to use this construct. – Tim Pietzcker Mar 06 '12 at 11:16
3

from ... import * is the bad style not recommended by PEP8 (python style guide). There are no ways to know which module is function from except the editing the code (replacing from ... impot * to 'import ...' and looking for errors). Unfortunately, those errors will occur only when corresponding parts of code is executed.

citxx
  • 2,525
  • 17
  • 40