tags:

views:

91

answers:

3

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?

+8  A: 

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.

Wim
This __package__ attribute is really cool, but seems to be unavailable. Is it available in python 2.5.2?
Stephen Gross
Ah no, it seems new in Python 2.6: http://www.python.org/doc/2.6/whatsnew/2.6.html#pep-366-explicit-relative-imports-from-a-main-module
Wim
Ok, so I researched the __package__ thing a bit. What I can't tell is whether the value is added by default, or if I have to specify something. I tried importing an empty module ("z.xx"), and z.xx.__package__ returned None. Am I doing something wrong?
Stephen Gross
Not sure, I can't seem to get it set either. It seems the `runpy` module is the only one actually using it. What information did you hope to get from it?
Wim
A: 

Try this:

help(foo.func_name)
inspectorG4dget
+1  A: 

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.

unutbu
+1 because this is a valid point, although it may not solve the problem (if the questioner wants to know where the function came from programmatically, having `from bar import foo` is basically the same)
dbr