function name

Alf P. Steinbach alfps at start.no
Wed Apr 28 15:20:55 EDT 2010


* Richard Lamboj:
>
> is there any way to get the name from the actual called function, so that the
> function knows its own name?

There was an earlier thread about this not very long ago.

General consensus, as I recall, to replace function with an object of a class 
(possibly with __call__ method if it is to be function-like, "functor").

An alternative is to treat the function itself as an object. I posted code for a 
decorator to help do that. Of course today I deleted that code (I just use a 
single 'x.py' file for various examples), but you may find it by Googling; 
however, I recommend the consensus view of "real" object.

A third way, even less desirable IMVHO, might be to use introinspection.

Let's see, ... reusing that 'x.py' file again ...

<code file="x.py">
#Py3

import inspect

def foo():
     frame = inspect.currentframe()
     info = inspect.getframeinfo( frame )
     print( info )

foo()
</code>

<output>
Fatal Python error: Py_Initialize: can't initialize sys standard streams
Traceback (most recent call last):
   File "C:\Program Files\cpython\python31\lib\encodings\__init__.py", line 31, 
in <module>
     import codecs
   File "C:\Program Files\cpython\python31\lib\codecs.py", line 8, in <module>
     """#"
KeyboardInterrupt

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
</output>


Oh my, I crashed the Python interpreter! This is my third time stumbling upon a 
crash-the-interpreter bug in CPython 3.x. I think I'm good at crashing things.

But OK, let's see. Well. Hm.


<code file="x.py">
#Py3

import inspect

def foo():
     frame = None; info = None; s = None;
     frame = inspect.currentframe()
     info = inspect.getframeinfo( frame )
     s = "Pleased to meet you, I was originally called '{}'!".format( 
info.function )
     print( s )

bar = foo
del foo

bar()
</code>

<output>
Pleased to meet you, I was originally called 'foo'!
</output>


But as mentioned, I'd personally choose a "real" object instead of a bare function.


Cheers & hth.,

- Alf



More information about the Python-list mailing list