Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Can a function access its own name?

26 views
Skip to first unread message

bobu...@yahoo.com

unread,
Nov 19, 2005, 12:52:20 PM11/19/05
to
Look at the code below:

# mystringfunctions.py

def cap(s):
print s
print "the name of this function is " + "???"

cap ("hello")


Running the code above gives the following output

>>>
hello
the name of this function is ???
>>>

I would like the output to be

>>>
hello
the name of this function is cap
>>>

Is that possible ?

Diez B. Roggisch

unread,
Nov 19, 2005, 1:09:18 PM11/19/05
to

Yes, use the moduloe inspect to access the current stack frame:

def handle_stackframe_without_leak():
frame = inspect.currentframe()
try:
print inspect.getframeinfo(frame)[2]
finally:
del frame

Diez

Peter Hansen

unread,
Nov 19, 2005, 1:19:59 PM11/19/05
to
bobu...@yahoo.com wrote:
[edited slightly]
> def cap():

> print "the name of this function is " + "???"
> cap ()

sys._getframe() would help you here:

>>> import sys
>>> sys._getframe()
<frame object at 0x00B496D0>
>>> def f():
... global x
... x = sys._getframe()
...
>>> f()
>>> x
<frame object at 0x00B15250>
>>> dir(x)
[..., 'f_builtins', 'f_code', 'f_exc_traceback', 'f_exc_type', ...]
>>> dir(x.f_code)
[...'co_name', 'co_names', 'co_nlocals', 'co_stacksize', 'co_varnames']
>>> x.f_code.co_name
'f'

So your function could be:

>>> import sys
>>> def cap():
... print 'function name is', sys._getframe().f_code.co_name
...
>>> cap()
function name is cap


-Peter

bobu...@yahoo.com

unread,
Nov 19, 2005, 2:55:03 PM11/19/05
to
Thanks Diez and Peter,

Just what I was looking for. In "Library Reference" heading

3.11.1 Types and members

I found the info about the method you described. I also made a little
function to print out not just the name of the function but also the
parameter list. Here it is

# fname.py
import sys, string

def cap(s, n):
print string.replace("".join([sys._getframe().f_code.co_name, \
repr(sys._getframe().f_code.co_varnames)]), "\'", "")

cap('Hello', 'Bob')

Running this yields the result

cap(s, n)

B Mahoney

unread,
Nov 19, 2005, 10:40:28 PM11/19/05
to
Decorate any function with @aboutme(), which
will print the function name each time the function is called.

All the 'hello' stuff is in the aboutme() decorator code.
There is no code in the decorated functions themselves
doing anything to telling us the function name.


# The decorator
def aboutme():

def thecall(f, *args, **kwargs):
# Gets to here during module load of each decorated function

def wrapper( *args, **kwargs):
# Our closure, executed when the decorated function is called
print "Hello\nthe name of this function is '%s'\n" \
% f.func_name
return f(*args, **kwargs)

return wrapper

return thecall

@aboutme()
def testing(s):
print "string '%s' is argument for function" % s


@aboutme()
def truing():
return True

# Try these
testing('x')

testing('again')

truing()

Mike Meyer

unread,
Nov 19, 2005, 11:30:32 PM11/19/05
to
bobu...@yahoo.com writes:
> Thanks Diez and Peter,
> Just what I was looking for. In "Library Reference" heading
> 3.11.1 Types and members
> Running this yields the result
>
> cap(s, n)

You've now got three solutions. They'll work fine most of the time,
but can't be trusted in general. Binding a name to a function doesn't
change the name that these solutions return, and the name they return
may no longer be bound to said function. Just a warning.

<mike
--
Mike Meyer <m...@mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.

Bengt Richter

unread,
Nov 20, 2005, 1:43:31 AM11/20/05
to
On Sat, 19 Nov 2005 23:30:32 -0500, Mike Meyer <m...@mired.org> wrote:

>bobu...@yahoo.com writes:
>> Thanks Diez and Peter,
>> Just what I was looking for. In "Library Reference" heading
>> 3.11.1 Types and members
>> Running this yields the result
>>
>> cap(s, n)
>
>You've now got three solutions. They'll work fine most of the time,
>but can't be trusted in general. Binding a name to a function doesn't
>change the name that these solutions return, and the name they return
>may no longer be bound to said function. Just a warning.
>

But the one buried in co_name seems to persist
(barring byte code munging in the decorator ;-)

>>> def fren(newname='newname'):
... def fren(f):
... f.__name__ = newname
... return f
... return fren
...
>>> @fren('bar')
... def foo():pass
...

Could have done that manually, but just playing.
Ok, rebind foo and remove the old name, for grins
>>> baz = foo
>>> del foo

See what we've got
>>> dir()
['__builtins__', '__doc__', '__name__', 'baz', 'fren']

Check name(s) ;-)
Local binding to the function object first:
>>> baz
<function bar at 0x02EEADF4>

Its outer name:
>>> baz.func_name
'bar'

Its def name:
>>> baz.func_code.co_name
'foo'

Regards,
Bengt Richter

Fredrik Lundh

unread,
Nov 20, 2005, 4:01:39 AM11/20/05
to pytho...@python.org
"B Mahoney" wrote:

> Decorate any function with @aboutme(), which
> will print the function name each time the function is called.
>
> All the 'hello' stuff is in the aboutme() decorator code.
> There is no code in the decorated functions themselves
> doing anything to telling us the function name.

so you've moved a trivial print statement from the function itself into
a decorator, so you can add an extra line before the function instead
of inside it. wow.

</F>

Fredrik Lundh

unread,
Nov 20, 2005, 4:03:18 AM11/20/05
to pytho...@python.org
bobu...@yahoo.com wrote:

def cap(s):
print s
print "the name of this function is " + "cap"

yes, I'm serious.

if your question had been "can a function figure out the name of the
function that called it", the answer would have been different.

</F>

0 new messages