function name

R

Richard Lamboj

Hello,

is there any way to get the name from the actual called function, so that the
function knows its own name?

Kind Regards,

Richi
 
P

Peter Otten

Richard said:
is there any way to get the name from the actual called function, so that
the function knows its own name?
.... return sys._getframe(1).f_code.co_name
........ print u"Ach, wie gut dass niemand weiß, dass ich", my_name().title(), u"heiß"
....Ach, wie gut dass niemand weiß, dass ich Rumpelstilzchen heiß

Peter
 
A

Alf P. Steinbach

* 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
 
T

Terry Reedy

* Richard Lamboj:

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
 
S

Steven D'Aprano

... return sys._getframe(1).f_code.co_name

Be aware though, that sys._getframe is marked as a private function (the
leading underscore), which means that:

(1) It only exists in some Python implementations (CPython and possible
nothing else?); and

(2) It is officially subject to change without warning, although that's
unlikely.


In practice, it's probably safe to use, but be aware that you are using a
documented internal feature.
 
P

Peter Otten

Steven said:
Be aware though, that sys._getframe is marked as a private function (the
leading underscore), which means that:

(1) It only exists in some Python implementations (CPython and possible
nothing else?); and

$ jython
Jython 2.2.1 on java1.6.0_0
Type "copyright", "credits" or "license" for more information.'f'

$ ipy
IronPython 1.1.1 (1.1.1) on .NET 2.0.50727.1433
Copyright (c) Microsoft Corporation. All rights reserved.Traceback (most recent call last):
ValueError: _getframe is not implemented
A quick websearch unearthed

http://blogs.msdn.com/dinoviehland/archive/2009/12/11/ironpython-2-6-
released.aspx

"""
IronPython 2.6 Released!

[...]

This release also changes how we support sys._getframe: a fully working
version is now available by a command line option; when not enabled
sys._getframe doesn’t exist at all.
"""

Peter
 

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,755
Messages
2,569,537
Members
45,021
Latest member
AkilahJaim

Latest Threads

Top