Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the function name as string in Python? [duplicate]

Tags:

python

Possible Duplicate:
How to get the function name as string in Python?

I know that I can do that :

def func_name():
    print func_name.__name__

which will return the name of the function as 'my_func'.

But as I am into the function, is there a way to directly call it generically ? Something like :

def func_name():
    print self.__name__

In which Python would understand that I want the upper part of my code hierarchy?

like image 297
jlengrand Avatar asked Sep 15 '11 14:09

jlengrand


People also ask

How do you print a function name as a string in Python?

You can get a function's name as a string by using the special __name__ variable.

What is __ func __ in Python?

It's this method object that has the __func__ attribute, which is just a reference to the wrapped function. By accessing the underlying function instead of calling the method, you remove the typecheck, and you can pass in anything you want as the first argument.

How do you read a function name in Python?

Method 1: Get Function Name in Python using function. func_name. By using a simple function property function, func_name, one can get the name of the function and hence can be quite handy for the Testing purpose and also for documentation at times. The drawback is that this works just for Python2.

Can two Python functions have the same name?

Python does not support function overloading. When we define multiple functions with the same name, the later one always overrides the prior and thus, in the namespace, there will always be a single entry against each function name.


2 Answers

Not generically, but you can leverage inspect

import inspect

def callee():
    return inspect.getouterframes(inspect.currentframe())[1][1:4][2]

def my_func():
    print callee() // string my_func

Source http://code.activestate.com/recipes/576925-caller-and-callee/

like image 160
John Giotta Avatar answered Oct 09 '22 15:10

John Giotta


AFAIK, there isn't. Besides, even your first method is not totally reliable, since a function object can have multiple names:

In [8]: def f(): pass
   ...: 

In [9]: g = f

In [10]: f.__name__
Out[10]: 'f'

In [11]: g.__name__
Out[11]: 'f'
like image 35
NPE Avatar answered Oct 09 '22 15:10

NPE