472,958 Members | 1,768 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,958 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 2746
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...
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
2
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

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.