473,396 Members | 2,082 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

getting the current function

Alex Martelli has a cookbook recipe, whoami, for retrieving the name of the current function: http://aspn.activestate.com/ASPN/Coo...n/Recipe/66062. It uses sys._getframe(). I'm a little wary about using sys._getframe() because of the underscore prefix and the fact that the python docs say "This function should be used for internal and specialized purposes only."

I feel more comfortable using the equivalent functionality in the inspect module.

Also, I wanted a way to get access to the current function, not just its name.

I came up with:

import inspect

def thisfunc(n=0):
currentFrame = inspect.currentframe()
outerFrames = inspect.getouterframes(currentFrame)
callingFrame = outerFrames[n + 1][0]
callersCallingFrame = outerFrames[n + 2][0]
return callersCallingFrame.f_locals[callingFrame.f_code.co_name]

The n argument lets you go up the stack to get callers of callers if that's convenient. For instance:

def attr(name, value):
caller = thisfunc(1)
if not hasattr(caller, name):
setattr(caller, name, value)

def x():
attr('counter', 0)
thisfunc().counter += 1
print thisfunc().counter

x()
x()
x()

Returns the output

1
2
3

Of course you don't need an attr() function for creating a function attribute, but this way your code won't break if you change the name of the function.

I was about to create a cookbook recipe, but decided to ask for some feedback from the community first.

Do you see situations where this function wouldn't work right?

Also, the python docs warn about storing frame objects due to the possibility of reference cycles being created (http://docs.python.org/lib/inspect-stack.html). But I don't think that's a worry here since thisfunc() stores the references on the stack rather than the heap. But I'm not sure. Obviously, it would be easy to add a try/finally with appropriate del's, but I don't want to do it if it's not necessary.

I welcome feedback of any type.

Thanks,
Gary


--

Gary Robinson
CTO
Emergent Music, LLC
ga*****@mac.com
207-942-3463
Company: http://www.goombah.com
Blog: http://www.garyrobinson.net
Sep 6 '07 #1
1 2786
On Sep 6, 8:43 am, Gary Robinson <gary...@mac.comwrote:
>
I welcome feedback of any type.
This all seems a bit too complicated. Are you sure you want to do
this? Maybe you need to step back and rethink your problem.

Your example can be rewritten a number of different ways that are
easier to think about.

The simple approach:

_x_counter = 0
def x():
_x_counter += 1
return _x_counter

The generator approach:

def counter_gen():
x = 0
while True:
x += 1
yield x

counter = counter_gen()
counter.next()
counter.next() # etc...

A class-based approach:

class Counter(object):
def __init__(self):
self._x = 0

def count(self):
self._x += 1
return self._x

In general, there really isn't a need to mess with stack frames unless
you are really interested in looking at the stack frame.

Sep 6 '07 #2

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

Similar topics

303
by: mike420 | last post by:
In the context of LATEX, some Pythonista asked what the big successes of Lisp were. I think there were at least three *big* successes. a. orbitz.com web site uses Lisp for algorithms, etc. b....
3
by: Beryl Small | last post by:
Hi, I have a third party software that needs to send information to an .aspx page for processing to communicate with an SQL database. The software sends the information something like this: ...
11
by: KarimL | last post by:
Thanks for your advices... but i need to get the Image height because i dynamically resize the height of my webcontrol based on the image height. More i just have the url (relative parth) to the...
11
by: singlal | last post by:
Hi, I am currently using DAYOFWEEK function and putting CASE statement to get english day name. For example: SELECT CASE DAYOFWEEK(CURRENT DATE) WHEN 1 THEN 'SUNDAY' WHEN 2 THEN 'MONDAY'
1
by: John Wilhelm | last post by:
I'm having a problem in by VB.net 2005 application. When i try to get a node from my app.config file the node come back with "nothing". The xmldocment loads OK, but I can't retrive a node. The...
1
by: pukya78 | last post by:
Hi, I am trying to get the current file and the line number which is getting executed. I used: MessageBox.Show(New StackTrace(New StackFrame(True)).GetFrame(0).GetFileLineNumber) which gives me...
1
davydany
by: davydany | last post by:
Hey guys...a n00b Here for this site. I'm making a sequence class for my C++ class. And The thing is in the array that I have, lets say i put in {13,17,38,18}, when i see the current values for the...
1
by: simbarashe | last post by:
Hie could someone please help me with getting and using the current page url. I have a function that gets the url, I want to use it with header(location : XXX) but it wont work. The code is as...
30
by: Ashit Vora | last post by:
Hi, I want to find the current time stamp in micro sec precision. The requirement is, my function is executed in an infinite loop. I measure a value and check if the value computed is what i...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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...
0
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,...
0
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...
0
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...
0
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...
0
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,...

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.