473,569 Members | 2,575 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How can I programmaticall y find the name of a method from within that method?

Is there a way that I can programmaticall y find the name of a method I
have created from within that method? I would like to be able to log
a message from within that method (def) and I would like to include
the name of the method from which it was written without having to
hard-code that value in every message string. While we're at it, is
there a way to programmaticall y get the name of the class and the
module while I'm at it?

Thanks,

Aug 8 '07 #1
9 2084
kj7ny wrote:
Is there a way that I can programmaticall y find the name of a method I
have created from within that method? I would like to be able to log
a message from within that method (def) and I would like to include
the name of the method from which it was written without having to
hard-code that value in every message string. While we're at it, is
there a way to programmaticall y get the name of the class and the
module while I'm at it?
This is a frequently asked question around here :-)

You should search the list archives for past threads, e.g:
http://aspn.activestate.com/ASPN/Mai...n-list/3542665

-Jay
Aug 8 '07 #2
On Aug 7, 10:09 pm, Jay Loden <pyt...@jaylode n.comwrote:
kj7ny wrote:
Is there a way that I can programmaticall y find the name of a method I
have created from within that method? I would like to be able to log
a message from within that method (def) and I would like to include
the name of the method from which it was written without having to
hard-code that value in every message string. While we're at it, is
there a way to programmaticall y get the name of the class and the
module while I'm at it?

This is a frequently asked question around here :-)

You should search the list archives for past threads, e.g:http://aspn.activestate.com/ASPN/Mai...n-list/3542665

-Jay
Thanks for the link. I had actually searched the past threads, but
apparently didn't enter the right search criteria because I did not
find that thread. Or, that thread isn't findable by searching Google
groups?

I tried the example in the interpreter and it appears to work.
Despite my years and years of programming in python, I am a bit
baffled by the example though. What is @checkPrivs (see example
copied below from other post)? In fact... how does the thing work at
all?

------------------------------------------
def checkPrivs(fn):
fnName = fn.func_name
def restricted(*arg s):
print "about to call function", fnName
if fnName in listOfAllowedFu nctions:
return fn(*args)
else:
raise KeyError("you don't have sufficient privileges to do
THAT")
return restricted

listOfAllowedFu nctions = ['add','subtract ']

@checkPrivs
def add(a,b):
return a+b

@checkPrivs
def subtract(a,b):
return a-b

@checkPrivs
def multiply(a,b):
return a*b

add(1,2)
subtract(4,1)
multiply(3,2)

Aug 8 '07 #3
kj7ny wrote:
What is @checkPrivs (see example copied below from other post)? In
fact... how does the thing work at all?
@checkPrivs
def add(a,b):
return a+b
@... is called a decorator and is just a fancy way of writing

def add(a, b):
return a+b
add = checkPrivs(add)

Peter
Aug 8 '07 #4
On Aug 8, 8:25 am, Peter Otten <__pete...@web. dewrote:
kj7ny wrote:
What is @checkPrivs (see example copied below from other post)? In
fact... how does the thing work at all?
@checkPrivs
def add(a,b):
return a+b

@... is called a decorator and is just a fancy way of writing

def add(a, b):
return a+b
add = checkPrivs(add)

Peter
Is this cheating?

class a:
def square(self, x):

print 'executing:', dir(self)[-1]
print x*x
def cube(self, x):
print 'executing:', dir(self)[-2]
print x*x*x

b=a()

b.square(3)
b.cube(3)
Output:

PyMate r6780 running Python 2.3.5 (python)
>>function self naming2.py
executing: square
9
executing: cube
27

Aug 8 '07 #5
Tony wrote:
Is this cheating?
Isn't it harder to calculate the magic indices than just writing down the
names twice?
class a:
********def square(self, x):
*************** *print 'executing:', dir(self)[-1]
*************** *print x*x
********def cube(self, x):
*************** *print 'executing:',** ***dir(self)[-2]
*************** *print x*x*x

b=a()
b.square(3)
b.cube(3)
Output:

PyMate r6780 running Python 2.3.5 (python)
>function self naming2.py

executing: square
9
executing: cube
27
Is this cheating?
No, just wrong.
>class A:
.... def alpha(self): return dir(self)[-2]
.... def gamma(self): return dir(self)[-1]
....
>>a = A()
a.alpha(), a.gamma()
('alpha', 'gamma')
>>a.beta = 42
a.alpha(), a.gamma()
('beta', 'gamma')

Peter
Aug 8 '07 #6
On Aug 8, 9:28 pm, Peter Otten <__pete...@web. dewrote:
No, just wrong.
class A:

... def alpha(self): return dir(self)[-2]
... def gamma(self): return dir(self)[-1]
...>>a = A()
>a.alpha(), a.gamma()
('alpha', 'gamma')
>a.beta = 42
a.alpha(), a.gamma()

('beta', 'gamma')

Peter
Only wrong if the function is only to write its own name. if it does
something else as well, seems to work:

class a:

def square(self, x):
print 'executing:', dir(self)[-1]
print x*x
def cube(self, x):
print 'executing:', dir(self)[-2]
print x*x*x

b=a()

b.cube(4),b.squ are(2)
b.c =4
b.cube(3), b.cube(2)

executing: cube
64
executing: square
4
executing: cube
27
executing: cube
8

cheers

Aug 8 '07 #7
On Aug 8, 12:45 am, kj7ny <kj...@nakore.c omwrote:
Is there a way that I can programmaticall y find the name of a method I
have created from within that method? I would like to be able to log
a message from within that method (def) and I would like to include
the name of the method from which it was written without having to
hard-code that value in every message string. While we're at it, is
there a way to programmaticall y get the name of the class and the
module while I'm at it?

Thanks,
def foo():
print sys._getframe(0 ).f_code.co_nam e

most of the darkest magic of python is in the frames returned by
sys._getframe.

Aug 9 '07 #8
On Aug 8, 10:43 pm, faulkner <faulkner...@gm ail.comwrote:
On Aug 8, 12:45 am, kj7ny <kj...@nakore.c omwrote:
Is there a way that I can programmaticall y find the name of a method I
have created from within that method? I would like to be able to log
a message from within that method (def) and I would like to include
the name of the method from which it was written without having to
hard-code that value in every message string. While we're at it, is
there a way to programmaticall y get the name of the class and the
module while I'm at it?
Thanks,

def foo():
print sys._getframe(0 ).f_code.co_nam e

most of the darkest magic of python is in the frames returned by
sys._getframe.
sorry for the double-post. i forgot to answer the rest of the
question.

class a:
def b(self, *a):
print sys._getframe(0 ).f_code.co_nam e
print self.__class__. __name__
print getattr(self,
sys._getframe(0 ).f_code.co_nam e).im_class.__n ame__
print self.__class__. __module__

def log(f):
def newf(*a, **kw):
if a and f.func_code.co_ varnames[0] == 'self': print '%s.%s.%s
%r %r' % (a[0].__class__.__mo dule__, a[0].__class__.__na me__,
f.func_name, a, kw)
else: print '%s.%s %r %r' % (f.func_globals['__name__'],
f.func_name, a, kw)
f(*a, **kw)
newf.__name__ = f.__name__
newf.__doc__ = f.__doc__
return newf

you can find more interesting attributes of frame and function objects
using the builtin dir function.

Aug 9 '07 #9
Tony wrote:
On Aug 8, 9:28 pm, Peter Otten <__pete...@web. dewrote:
>No, just wrong.
>class A:

... def alpha(self): return dir(self)[-2]
... def gamma(self): return dir(self)[-1]
...>>a = A()
>>a.alpha(), a.gamma()
('alpha', 'gamma')
>>a.beta = 42
a.alpha(), a.gamma()

('beta', 'gamma')

Peter
Only wrong if the function is only to write its own name. if it does
something else as well, seems to work:

class a:

********def square(self, x):
*************** *print 'executing:', dir(self)[-1]
*************** *print x*x
********def cube(self, x):
*************** *print 'executing:',** ***dir(self)[-2]
*************** *print x*x*x

b=a()

b.cube(4),b.squ are(2)
b.c =4
b.cube(3), b.cube(2)
You mean

b.cube(3), b.square(2)
executing: cube
64
executing: square
4
executing: cube
27
executing: cube
8
Yeah, cargo cult programming, I love it.

dir() sorts attribute names alphabetically. Therefore the tail of the list
you are accessing will only be altered if you choose a name >
min(other_names ), i. e. a name that comes after "cube" in the alphabet. Try
setting

b.root = 42

if you don't believe me.

Peter
Aug 9 '07 #10

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

Similar topics

4
5972
by: Victor Hadianto | last post by:
Hi, If I have an XmlDocument DOM how do I insert <?mso-application progid="ProgId.Here"?> programmatically? -- Victor Hadianto http://www.synop.com/Products/SauceReader/
20
3387
by: 2pac | last post by:
in this scenario foo1 ---calls---> foo2 is it possible for me to print out - when the control is within foo2 - the caller of foo2 the information is obviously there in the stack - am wondering if by some combination of assembly and pointer manipulation - I can print the name of the caller of the method Thanks for any suggestions
5
1723
by: Helen | last post by:
Hi, I am trying to write an ASP.Net application that integrates with a third party application via their fairly simplistic web component, however I am having problems with the URI. The URI works fine in Internet Explorer, and returns the information from the third party application to the browser, which is displayed, no problems.
3
2448
by: eSolTec, Inc. 501(c)(3) | last post by:
Thank you in advance for any and all assistance, it is GREATLY appreciated. I'm wondering if there is a way to duplicate a function in regedit of find and find next for keywords programmatically, then to list them in a treeview or listbox? If so, could someone point me to some code? -- Michael Bragg, President eSolTec, Inc. a 501(C)(3)...
7
27823
by: Dale Sampson | last post by:
As you can tell, I am new to VS.net. I have a VB project with a defined data source pointing to a table in a ..mdb file.-- The associated fields are displayed in textboxes using the tableBindingSource. There is also an associated BindingNavigator. The table's primary key is a field called 'who'. I have a valid value for 'who' and want to set...
3
2751
by: Merk | last post by:
How can I programmatically determine the from within that method. For example, consider the following code: private void DoSomething() { string s = ???; }
5
17996
by: ~~~ .NET Ed ~~~ | last post by:
Well the subject says it all but I am going to elaborate a bit. As we all now since 2.0 it is possible to access the Header from code behind without much wizardry and that is a good thing. Now, in my site I am using master pages and one of the site pages (but could be more) needs certain customization in which the BODY tag needs the onLoad...
2
15053
by: ChrisCicc | last post by:
Hi All, I got a real doozy here. I have read hundreds upon hundreds of forum posts and found numerous others who have replicated this problem, but have yet to find a solution. Through testing I have been able to find the cause of the problem, and will describe it here first textually and then through a code example. The purpose of what I am...
3
2272
by: Peter | last post by:
Hi I want to programmatically perform a post. Can some one please give me some pointers to which classes I need to use to achieve this? The form which is normally posted from the website looks like the following, but I want to do it programmatically. <form action="https://intl.payments/recdpay" method="POST"
0
7711
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...
0
7628
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7938
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. ...
1
7694
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...
0
7993
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6317
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...
0
3667
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2128
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
970
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.