473,811 Members | 2,869 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.current frame()
outerFrames = inspect.getoute rframes(current Frame)
callingFrame = outerFrames[n + 1][0]
callersCallingF rame = outerFrames[n + 2][0]
return callersCallingF rame.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().coun ter += 1
print thisfunc().coun ter

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 2813
On Sep 6, 8:43 am, Gary Robinson <gary...@mac.co mwrote:
>
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
17813
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. Yahoo store was originally written in Lisp. c. Emacs The issues with these will probably come up, so I might as well mention them myself (which will also make this a more balanced
3
2001
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: Mypage.aspx?Password=Mypassword When this request hits the page, I need to pull that variable Mypassword to use in my VB function to query the database. I'm confused on how to get it. I tried using
11
2029
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 the image but in design time mode all variables concerning Server or Context ar not set ! ...so I can't use MapPath function to obtain the physical parth of the picture ... So my second question is how to retrieve the physical root path of the...
11
11742
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
2899
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 app.config file is listed below and the code is listed below that, the line with "-->>" is where i try to get the node. Can anyone see where I'm going wrong. A dump of the xmlDocument is listed below the code. Note: "MyKey" is set to "Reports"
1
1875
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 the line number. Later on, I was trying to write a generalized routine, so that I can log the file name and the method.
1
3030
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 array data from 0 to3, I get this {13, JUNK VALUE, 17,38, 18} and JUNK VALUE is like 1.8e831 or something like that. This happens when I use the attach() function and use the current() function to display the values at data I really want to...
1
3203
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 follows: The code below is for the first page:session_start is in line 3 <link href="css/jobSheet.css" rel="stylesheet" type="text/css" /> session_start();
30
521
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 expected 9forget all this stuff). I want to print the time stamp every time that event occurs. So my requirement is printing the current timestamps.
0
9722
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
9603
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10379
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
10393
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
10124
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9200
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
7664
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
5550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4334
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

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.