How to get function string name from i-th stack position?

Ian Kelly ian.g.kelly at gmail.com
Fri Dec 30 16:48:49 EST 2011


On Fri, Dec 30, 2011 at 11:43 AM, dmitrey <dmitrey15 at gmail.com> wrote:
> Thank you. And what should I do to get function by itself instead of
> its string name, e.g. I want to know does this function is my_func or
> any other? For example, I would like to check is this function Python
> sum(), or maybe numpy.sum(), or anything else?

The Python stack only includes Python code objects.  Built-ins like
sum won't appear in it because they're basically C functions and don't
have associated code objects.  If you really want to see them, you
could probably do something with ctypes to inspect the C stack, but I
don't recommend it.

You can get the Python code objects from the stack by calling
inspect.stack(), which includes each frame object currently on the
stack as the first member of each tuple.  E.g.:

frames = map(operator.itemgetter(0), inspect.stack())

Each frame has an f_code attribute that stores the code object
associated with that frame.  Getting the actual function from the code
object is tricky, for two reasons.  One, not all code objects
represent functions.  There are also code objects for modules, class
definitions, and probably other thing as well.  Two, code objects
don't have associated functions. The relationship is the reverse:
functions have associated code objects.  You would have to iterate
over each function that you're interested in, looking for one with a
func_code attribute that "is" the frame's f_code attribute.

In any case, testing function identity is a rather large rabbit hole
that is best avoided.  These are mathematically the same function:

def plus1(value):
    return value + 1

plus_one = lambda x: x + 1

But they are two distinct function objects, and there is no way
programmatically to determine that they are the same function except
by comparing the bytecode (which won't work generally because of the
halting problem).

What is it that you're trying to do?  Perhaps the helpful folks on the
list will be able to suggest a better solution if you can provide more
details.

Cheers,
Ian



More information about the Python-list mailing list