Can a function access its own name?

B

bobueland

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 ?
 
D

Diez B. Roggisch

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
 
P

Peter Hansen

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

sys._getframe() would help you here:
.... global x
.... x = sys._getframe()
....
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:
.... print 'function name is', sys._getframe().f_code.co_name
....function name is cap


-Peter
 
B

bobueland

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

B Mahoney

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()
 
M

Mike Meyer

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
 
B

Bengt Richter

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(f):
... f.__name__ = newname
... return f
... return fren
... ... def foo():pass
...

Could have done that manually, but just playing.
Ok, rebind foo and remove the old name, for grins
See what we've got ['__builtins__', '__doc__', '__name__', 'baz', 'fren']

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

Its outer name: 'bar'

Its def name: 'foo'

Regards,
Bengt Richter
 
F

Fredrik Lundh

B Mahoney said:
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>
 
F

Fredrik Lundh

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>
 

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

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top