Stephen Gross
Stephen Gross

Reputation: 5724

How to find where a function was imported from in Python?

I have a Python module with a function in it:

  == bar.py ==
  def foo(): pass
  == EOF ==

And then I import it into the global namespace like so:

from bar import *

So now the function foo is available to me. If I print it:

print foo

The interpreter happily tells me:

 <function foo at 0xb7eef10c>

Is there a way for me to find out that function foo came from module bar at this point?

Upvotes: 14

Views: 6778

Answers (4)

flow2k
flow2k

Reputation: 4357

If you have IPython, you can also use ?:

In[16]: runfile?
Signature: runfile(filename, args=None, wdir=None, is_module=False, global_vars=None)
Docstring:
Run filename
args: command line arguments (string)
wdir: working directory
File:      /Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_umd.py
Type:      function

Compare with __module__:

In[17]:  runfile.__module__
Out[17]: '_pydev_bundle.pydev_umd'

Upvotes: 0

unutbu
unutbu

Reputation: 880907

Instead of

from bar import *

use

from bar import foo

Using the from ... import * syntax is a bad programming style precisely because it makes it hard to know where elements of your namespace come from.

Upvotes: 1

inspectorG4dget
inspectorG4dget

Reputation: 114035

Try this:

help(foo.func_name)

Upvotes: 3

Wim
Wim

Reputation: 11252

foo.__module__ should return bar

If you need more info, you can get it from sys.modules['bar'], its __file__ and __package__ attributes may be interesting.

Upvotes: 24

Related Questions