开发者

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 nam开发者_JS百科espace 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?


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.


Try this:

help(foo.func_name)


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.


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'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜