473,775 Members | 2,592 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can a function access its own name?

Look at the code below:

# mystringfunctio ns.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
16 2037
bo*******@yahoo .com wrote:
Look at the code below:

# mystringfunctio ns.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_stackfra me_without_leak ():
frame = inspect.current frame()
try:
print inspect.getfram einfo(frame)[2]
finally:
del frame

Diez
Nov 22 '05 #2
bo*******@yahoo .com wrote:
Look at the code below:

# mystringfunctio ns.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_stackfra me_without_leak ():
frame = inspect.current frame()
try:
print inspect.getfram einfo(frame)[2]
finally:
del frame

Diez
Nov 22 '05 #3
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_tracebac k', 'f_exc_type', ...] dir(x.f_code) [...'co_name', 'co_names', 'co_nlocals', 'co_stacksize', 'co_varnames'] x.f_code.co_nam e '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
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_tracebac k', 'f_exc_type', ...] dir(x.f_code) [...'co_name', 'co_names', 'co_nlocals', 'co_stacksize', 'co_varnames'] x.f_code.co_nam e '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
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._getfr ame().f_code.co _varnames)]), "\'", "")

cap('Hello', 'Bob')

Running this yields the result

cap(s, n)

Nov 22 '05 #6
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._getfr ame().f_code.co _varnames)]), "\'", "")

cap('Hello', 'Bob')

Running this yields the result

cap(s, n)

Nov 22 '05 #7
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
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
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.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Nov 22 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
4964
by: Penn Markham | last post by:
Hello all, I am writing a script where I need to use the system() function to call htpasswd. I can do this just fine on the command line...works great (see attached file, test.php). When my webserver runs that part of the script (see attached file, snippet.php), though, it doesn't go through. I don't get an error message or anything...it just returns a "1" (whereas it should return a "0") as far as I can tell. I have read the PHP...
58
10181
by: jr | last post by:
Sorry for this very dumb question, but I've clearly got a long way to go! Can someone please help me pass an array into a function. Here's a starting point. void TheMainFunc() { // Body of code... TCHAR myArray; DoStuff(myArray);
13
3497
by: Maroon | last post by:
Hi, I want to write a standard java user defined function, like this example:- select db_fun("roll"), roll from student; **db_fun() will work for all tables of the all databse here db_fun is the function that i want to write. The student table is:- roll name 1 'A'
9
1802
by: JC | last post by:
The following function creates a display name from a and and . I call the function from a query. When I run the query those records that have BOTH a his and her name appear correctly, but if one of the names is blank "#ERROR" appears in the field where the combined name should appear. Why doesn't the function process the else statement correctly? The If statement works just fine. Thank you in advance. - jc -
6
4410
by: Bill Rubin | last post by:
The following code snippet shows that VC++ 7.1 correctly compiles a static member function invocation from an Unrelated class, since this static member function is public. I expected to compile the same invocation from a DistantlyRelated class. What actually happened was that the compiler produced: error C2247: 'A::function' not accessible because 'CloselyRelated' uses 'private' to inherit from 'A' I'm guessing that the above compiler...
5
7463
by: Ram | last post by:
Hi Friends I want to develope a custom control in .net which can be used with any project. I am writing a function in that class which I want to take any object as parameter. For that I have used Object class as parameter. Now it can take any object as its parameter. But the problem is that I want to access the values of the private or public member variables of the passed object, for which I may have to typecast the Object class...
2
4852
by: Serious_Practitioner | last post by:
Good day, and thank you in advance for any assistance. I'm having trouble with something that I'm trying for the first time. Using Access 2000 - I want to run a function either on the click of a button or on leaving a text box. For the immediate task, either will work as well as the other. I think. I'm just at the beginning of this, and the form has two text boxes - Text0 and Text1. The user input to Text0 is a dollar amount, in...
4
17144
by: jj6849 | last post by:
I have been using the dom to add a row to my form for awhile now, but now I need to do some validation to make sure certain check boxes aren't checked with other check boxes. Now of course it works with the first row, but after I add a row, the Function does not work (no runtime error or anything). So first is my Function do the validation, second is my code for adding new row (this is where I'm having trouble, maybe with the setAttribute??),...
5
3846
by: wugon.net | last post by:
question: db2 LUW V8 UNION ALL with table function month() have bad query performance Env: db2 LUW V8 + FP14 Problem : We have history data from 2005/01/01 ~ 2007/05/xx in single big table, we try separate this big table into twelve tables and create a view
12
3018
by: Bryan Parkoff | last post by:
I write my large project in C++ source code. My C++ source code contains approximate four thousand small functions. Most of them are inline. I define variables and functions in the global scope. The global variables and global functions are hidden to prevent from accessing by the programmers. All global functions share global variables. Only very few global functions are allowed to be reusability for the programmers to use. Few...
0
9622
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10268
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10107
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10048
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8939
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7464
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6718
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5486
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3611
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.