On 4/28/2010 3:20 PM, Alf P. Steinbach wrote:
* 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.

Perhaps you push harder, perhaps you are more observant and persistent in verifying such things.

However, in this case, with "Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit (Intel)] on win32", I reproducibly get

Traceback(filename='C:\\Programs\\Python31\\misc\\t1.py', lineno=5, function='foo', code_context=[' info = inspect.getframeinfo( frame )\n'], index=0)

on fresh IDLE and

Traceback(filename='<stdin>', lineno=3, function='foo', code_context=None, index=None)

with a fresh command window. Both are more or less as expected. Were you using an earlier version? Different system? Did you run other code first?

Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to