By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,836 Members | 2,011 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,836 IT Pros & Developers. It's quick & easy.

Can a function access its own name?

P: n/a
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 ?

Nov 22 '05 #1
Share this Question
Share on Google+
16 Replies


P: n/a
bo*******@yahoo.com wrote:
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 ?


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
Nov 22 '05 #2

P: n/a
bo*******@yahoo.com wrote:
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 ?


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
Nov 22 '05 #3

P: n/a
bo*******@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
Nov 22 '05 #4

P: n/a
bo*******@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
Nov 22 '05 #5

P: n/a
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)

Nov 22 '05 #6

P: n/a
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)

Nov 22 '05 #7

P: n/a
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()

Nov 22 '05 #8

P: n/a
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()

Nov 22 '05 #9

P: n/a
bo*******@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 <mw*@mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Nov 22 '05 #10

P: n/a
bo*******@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 <mw*@mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Nov 22 '05 #11

P: n/a
On Sat, 19 Nov 2005 23:30:32 -0500, Mike Meyer <mw*@mired.org> wrote:
bo*******@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
Nov 22 '05 #12

P: n/a
On Sat, 19 Nov 2005 23:30:32 -0500, Mike Meyer <mw*@mired.org> wrote:
bo*******@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
Nov 22 '05 #13

P: n/a
"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>

Nov 22 '05 #14

P: n/a
bo*******@yahoo.com wrote:
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 ?


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>

Nov 22 '05 #15

P: n/a
"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>

Nov 22 '05 #16

P: n/a
bo*******@yahoo.com wrote:
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 ?


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>

Nov 22 '05 #17

This discussion thread is closed

Replies have been disabled for this discussion.