Get the name of a function

G

gervaz

Hi all, is there a way to retrive the function name like with
self.__class__.__name__?

Using self.__dict__.__name__ I've got
.... print(self.__dict__.__name__)
....<function test at 0x0178DDF8>

But I really just want the function name, so 'test'

Any help?

Thanks,

Mattia
 
E

Emile van Sebille

On 8/5/2011 11:52 AM gervaz said...
Hi all, is there a way to retrive the function name like with
self.__class__.__name__?

yes, but not reliably:

Python 2.6.4rc2 (r264rc2:75497, Oct 20 2009, 02:55:11)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.

Emile
 
C

Chris Rebert

Hi all, is there a way to retrive the function name like with
self.__class__.__name__?

Using self.__dict__.__name__ I've got

...     print(self.__dict__.__name__)
...

Er, where did `self` magically come from?
<function test at 0x0178DDF8>

But I really just want the function name, so 'test'

Any help?

Courtesy of the "Observations on the three pillars of Python execution" thread:

from inspect import currentframe

def foobar():
my_name = currentframe().f_code.co_name
print(my_name)

I would recommend against a function knowing its own name though,
unless it's for debugging or necessary metaprogramming purposes.

Cheers,
Chris
 
G

Grant Edwards

Hi all, is there a way to retrive the function name like with
self.__class__.__name__?

Not really. There may not be any such thing as "the function name". A
function may have zero names, it may have a dozen names. It may have
names but only in namespaces that aren't accessible.

This question comes up at least once a month, so look back through the
group for threads about finding an object's name, finding a
parameter's name, etc.

Here's a nice article on introspection, but what it talks about as a
"function name" probably isn't what you're interested in:

http://www.ibm.com/developerworks/library/l-pyint/index.html

Here's a stack-overflow question similar to yours:

http://stackoverflow.com/questions/1538342/how-can-i-get-the-name-of-an-object-in-python
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,067
Latest member
HunterTere

Latest Threads

Top