[Tutor] how to decypther which module function was imported from when from module import * is used

Remco Gerlich scarblac@pino.selwerd.nl
Mon, 28 May 2001 14:52:32 +0200


On  0, Michael Schmitt <lgwb@home.com> wrote:
> I am trying to read code that has several line off "from module import *"
> and I want to know how as I trying to read though the code how I decipher
> which module a function has been imported from when the fully-qualified name
> is not used.

In general, you can't. That's the problem with 'from module import *', and
one of the reasons why it's usually a bad idea.

There are some exceptions, like GUI toolkits - wxPython is usually used with
'from wxPython.wx import *' - but *its* objects have names like wxApp,
wxFrame, wxDialog - you can tell.

I suppose you can make a small function to use in the interpreter, like

def find_object(modulenames, name):
   modules = [__builtins__]+map(__import__, modulenames)
   modules.reverse()
   
   for mod in modules:
      if hasattr(mod, name):
         return mod.__name__
   return "Not found"

Now you can keep track of the imported modules and see where something would
come from. If the program does from...import * on sys, os and string, you
could do

>>> mods=["sys","os","string"]
>>> find_object(mods, "open")
'os'

And you see that the builtin open() would be overwritten by os.open().

(not tested)

-- 
Remco Gerlich