简体   繁体   中英

Determine which function was called

def f():
   return


g=f

g.func_name is "f"

How do I get "g"?

You can't.

EDIT: gc.get_referrers exists, but will not tell you which reference to a function object was used to call it, so it doesn't help you. In addition, there are certain caveats when using that function and I don't know whether it works under implementations other than CPython. Its use in production code is discouraged.

As a final note, while the FAQ may not be entirely correct about whether you can determine an object's name, its insights as to whether you should are dead-on.

When f is created by def , the __name__ attributed is created at the same time. That attribute is assigned to the function object and it persists no matter what you subsequently assign the function to.

In general, an object doesn't know which variables it points to.

However, we do have tools like gc.get_referrers() than use implementation specific logic to find all the references to an object:

>>> def f(x):
    return x**2

>>> g = f

>>> import gc
>>> gc.get_referrers(f)[0].keys()
['g', 'f', '__builtins__', '__package__', 'gc', '__name__', '__doc__']

Another technique is to scan a namespace for all instances of a particular object:

>>> [key for key, value in globals().items() if value == f]
['g', 'f']

You may be able to do it by inspecting the source code using inspect module, and only then with some limitations (at the very least, you'll need to be able to obtain the line where the name in question is mentioned).

You absolutely shouldn't do that unless you really know why you need it.

a = 1
b = 1
c = 1

What is the name of 1? Does that question even make sense?

A function is an object like any other, such as 1 or "cats" . It has a __name__ attribute that tells you what name it was originally defined as, but other names can be assigned to it, and no record is kept on the object of these assignments.

You can search all local and global variables for it, but this won't find every possible reference; references to the function can be held in containers such as dictionaries or lists, as object attributes, as globals in other modules, and probably other places I'm not thinking of right now. Oh. Closures, Still: this is the gist:

def f():
    pass

g = f

allvars = dict(globals())
allvars.update(locals())
funcnames = [key for (key, value) in allvars.iteritems() if value is f]
# returns ['g', 'f']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM