473,785 Members | 3,137 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

interface boilerplate


In matplotlib, a plotting library with an OO API and a matlab-like
procedural interface, I have a lot of functions defined in the matlab
interface module that wrap similarly named class methods defined in
the Axes class of the axes module. Eg, the Axes class defines a plot
method and the matlab interface defines a plot function that gets the
current Axes instance, calls the plot method on that instance, and
does some error handling. Here is the matlab interface wrapper (gca()
returns the current Axes instance)

def plot(*args, **kwargs):
try:
ret = gca().plot(*arg s, **kwargs)
except ValueError, msg:
msg = raise_msg_to_st r(msg)
error_msg(msg)
else:
draw_if_interac tive()
return ret
plot.__doc__ = Axes.plot.__doc __

This is mostly boilerplate code that a lot of matlab interface
functions use, and I'd like to automatically generate it.

This appears to (mostly) work

def _wrap_axfunc(na me):
def wrapper(*args, **kwargs):
try:
func = getattr(gca(), name)
ret = func(*args, **kwargs)
except ValueError, msg:
msg = raise_msg_to_st r(msg)
error_msg(msg)
else:
draw_if_interac tive()
return ret
wrapper.__doc__ = getattr(Axes, name).__doc__
#wrapper.__name __ = name
return wrapper

plot = _wrap_axfunc('p lot')

The only problem I've seen so far is that the name of the function in
pydoc string is 'wrapper', and I want it to appear as "plot". I tried
setting the __name__ attribute, but it is read only.

Any suggestions on how to best define these matlab interface functions
by automatically wrapping the Axes instance functions? I'd like to
support python2.2 so python2.2 compliant solutions especially welcome.

JDH
Jul 18 '05 #1
4 1530
John Hunter <jd******@ace.b sd.uchicago.edu > wrote:
...
The only problem I've seen so far is that the name of the function in
pydoc string is 'wrapper', and I want it to appear as "plot". I tried
setting the __name__ attribute, but it is read only.
Yes, a 2.3 problem, solved in 2.4.
Any suggestions on how to best define these matlab interface functions
by automatically wrapping the Axes instance functions? I'd like to
support python2.2 so python2.2 compliant solutions especially welcome.


Then I guess upgrading to 2.4 is out of the question.

To make a function just like another but with a different name:

def changed_name_fu nction(f, newname):
import new
return new.function(f. func_code, f.func_globals, newname,
f.func_defaults , f.func_closure)

I believe this should work in 2.2 as well (not tested).
Alex

Jul 18 '05 #2
>>>>> "Alex" == Alex Martelli <al*****@yahoo. com> writes:

Alex> To make a function just like another but with a different
Alex> name:

Alex> def changed_name_fu nction(f, newname): import new return
Alex> new.function(f. func_code, f.func_globals, newname,
Alex> f.func_defaults , f.func_closure)

Alex> I believe this should work in 2.2 as well (not tested).

I tested this - the signature of new.function in 2.2 is a bit
different

function(...)
Create a function object from (CODE, GLOBALS, [NAME [, ARGDEFS]]).

so it doesn't take the 5 arg version posted.

I am having a little trouble figuring out how to handle the call
signature for 2.2. I tried this modification (matplotlib._py thon23 is
a flag that returns True iff python version >=2.3
def changed_name_fu nction(f, newname):
import new
if matplotlib._pyt hon23:
newf = new.function(f. func_code, f.func_globals, newname,
f.func_defaults , f.func_closure)
else:
if f.func_defaults is None:
argdefs = ()
else:
argdefs = f.func_defaults
newf = new.function(f. func_code, f.func_globals, newname,
argdefs)

newf.__doc__ = f.__doc__
return newf

I added the None check on f.func_defaults because I was getting the
error

TypeError: function() argument 4 must be tuple, not None

But this does not appear to be right either because I get a segfault
:-( Note that the suggestion works as advertised for python2.3.

Any ideas?

Thanks,
John Hunter
Jul 18 '05 #3
John Hunter <jd******@ace.b sd.uchicago.edu > wrote:
>> "Alex" == Alex Martelli <al*****@yahoo. com> writes:

Alex> To make a function just like another but with a different
Alex> name:

Alex> def changed_name_fu nction(f, newname): import new return
Alex> new.function(f. func_code, f.func_globals, newname,
Alex> f.func_defaults , f.func_closure)

Alex> I believe this should work in 2.2 as well (not tested).

I tested this - the signature of new.function in 2.2 is a bit
different

function(...)
Create a function object from (CODE, GLOBALS, [NAME [, ARGDEFS]]).

so it doesn't take the 5 arg version posted.


Ah, it didn't take a closure. Could be quite a problem...
I am having a little trouble figuring out how to handle the call
signature for 2.2. I tried this modification (matplotlib._py thon23 is
a flag that returns True iff python version >=2.3
def changed_name_fu nction(f, newname):
import new
if matplotlib._pyt hon23:
newf = new.function(f. func_code, f.func_globals, newname,
f.func_defaults , f.func_closure)
else:
if f.func_defaults is None:
argdefs = ()
else:
argdefs = f.func_defaults
newf = new.function(f. func_code, f.func_globals, newname,
argdefs)

newf.__doc__ = f.__doc__
return newf

I added the None check on f.func_defaults because I was getting the
error

TypeError: function() argument 4 must be tuple, not None

But this does not appear to be right either because I get a segfault
:-( Note that the suggestion works as advertised for python2.3.

Any ideas?


Supporting old versions is never going to be easy -- I don't even have a
2.2 installation around to do such tests, any more. Perhaps for
versions < 2.3 you could simply degrade gracefully to perform no
renaming (and for versions >= 2.4 do the renaming the right way, by
assigning to f.func_name and returning f)... those who choose to stick
with 2.2 will just have to account that as one of the many limitations
and slow-downs their choice buys them...
Alex
Jul 18 '05 #4
>>>>> "Alex" == Alex Martelli <al*****@yahoo. com> writes:

Alex> Supporting old versions is never going to be easy -- I don't
Alex> even have a 2.2 installation around to do such tests, any
Alex> more. Perhaps for versions < 2.3 you could simply degrade
Alex> gracefully to perform no renaming (and for versions >= 2.4
Alex> do the renaming the right way, by assigning to f.func_name
Alex> and returning f)... those who choose to stick with 2.2 will
Alex> just have to account that as one of the many limitations and
Alex> slow-downs their choice buys them...

It is a pain -- for a fair number of linux boxes, though, 2.2 is still
the default. Perhaps a better alternative for 2.2 is to simply fall back on
exec

__fmt = """\
def %(name)s(*args, **kwargs):
try:
ret = gca().%(name)s( *args, **kwargs)
except ValueError, msg:
msg = raise_msg_to_st r(msg)
error_msg(msg)
else:
draw_if_interac tive()
return ret
%(name)s.__doc_ _ = Axes.%(name)s._ _doc__
"""

for name in _methods:
exec(__fmt%{'na me':name})
JDH
Jul 18 '05 #5

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

Similar topics

15
2598
by: Ralf W. Grosse-Kunstleve | last post by:
****************************************************************************** This posting is also available in HTML format: http://cci.lbl.gov/~rwgk/python/adopt_init_args_2005_07_02.html ****************************************************************************** Hi fellow Python coders, I often find myself writing:: class grouping:
4
8205
by: Roy Pereira | last post by:
I have an application that is composed of a set of "Content" dlls and a viewer application. The viewer calls a standard set of functions that are present in all the dlls. I maintain this by making my contnent dlls implement an interface created in vb6. The viewer application is bound to this interface. This way, I am able to add Content without redeploying the dlls (I just have to add the new dlls). I want to write new content for...
0
947
by: redog6 | last post by:
When I save my XML file as data the resulting XML includes the boilerplate text of my template. Is the approach to change my custom schema to allow mixed content or is there a way to exclude the boilerplate text? Any advice would be appreciated. Thanks Redge.
3
4143
by: zlst | last post by:
Many technological innovations rely upon User Interface Design to elevate their technical complexity to a usable product. Technology alone may not win user acceptance and subsequent marketability. The User Experience, or how the user experiences the end product, is the key to acceptance. And that is where User Interface Design enters the design process. While product engineers focus on the technology, usability specialists focus on the user...
2
1340
by: dwok | last post by:
Does anyone know of any "boilerplate" template that can be utilized to add/edit/delete information from a database? I am working on an application that does a whole lot of adds, edits, and updates and it seems like most of my code is very repetative. I have been looking to move everything into a class for re-use but before I did I wanted to see if there was anybody else who had done the same thing already. Thanks! - dwok
0
2511
by: YellowFin Announcements | last post by:
Introduction Usability and relevance have been identified as the major factors preventing mass adoption of Business Intelligence applications. What we have today are traditional BI tools that don't work nearly as well as they should, even for analysts and power users. The reason they haven't reached the masses is because most of the tools are so difficult to use and reveal so little
11
1600
by: Steven D'Aprano | last post by:
I'm writing a class that implements rich comparisons, and I find myself writing a lot of very similar code. If the calculation is short and simple, I do something like this: class Parrot: def __eq__(self, other): return self.plumage() == other.plumage() def __ne__(self, other): return self.plumage() != other.plumage()
15
2807
by: Xah Lee | last post by:
On Java's Interface Xah Lee, 20050223 In Java the language, there's this a keyword “interface”. In a functional language, a function can be specified by its name and parameter specs. For example: f(3) f(3, )
3
2154
by: n.torrey.pines | last post by:
Hi I work with a nested tree-like data structure template (that happens to be a tuple of vectors of tuples of trees of something, with different tuple elements having different types) I need to define a variety of ELEMENTWISE operations, like a. increment all leaves (unary) b. match two data structures (binary)
0
9643
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, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
10147
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...
0
9947
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...
1
7494
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
6737
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
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4045
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
2
3645
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2877
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.