473,396 Members | 1,871 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.

Trapping numeric operators

I want to trap numeric operators (+ * % etc.) so that my new style
classes can handle them generically, similar to __getattr__ in an old
style class.

I've never done any metaprogramming before but I'm thinking of using
the below metaclass to accomplish this. It reads a class variable,
implements_operators, to determine which methods handle various
operators, then inserts closures to call the generic methods with
disambiguating parameters (the name of the magic method and the
corresponding operator built-in, if it can be determined).

Is this a reasonable approach or an abuse of metaclasses? Any comments
would be deeply appreciated.

Thanks,
John

import operator # the metaclass
class metaOperator(type):
def __new__(cls, classname, bases, classdict):
fnDict = classdict['implements_operators']
for fn in fnDict.iterkeys():
for magicName in fnDict[fn]:
for opName in (magicName, '__%s'%magicName[3:]):
# try magicName else assume in-place/right
# and strip out the presumptive 'i'/'r'
try:
op = getattr(operator, opName)
break
except AttributeError:
pass
else:
op = None
classdict[magicName] = (
lambda self, other=None, name=magicName, op=op, fn=fn:
fn(self, other, name, op)
)
return type.__new__(cls, classname, bases, classdict)

class Q(object): # a sketch of its use
__metaclass__ = metaOperator

def binop(self, other, name, op): pass
def ibinop(self, other, name, op): pass
def unop(self, other, name, op): pass

implements_operators = {
binop: ('__add__','__sub__','__mul__','__div__'),
ibinop: ('__iadd__','__isub__','__imul__','__idiv__'),
unop: ('__neg__','__pos__','__abs__','__invert__'),
}
Jul 18 '05 #1
1 1400
The lambda wrapper does impose the overhead of an extra function call:
classdict[magicName] = (
lambda self, other=None, name=magicName, op=op, fn=fn:
fn(self, other, name, op)
)

I could eliminate that by stubbing out the closure and inserting the
code block directly into it:
stub = lambda self, other=None, name=magicName, op=op: self
stub.func_code = fn.func_code
classdict[magicName] = stub

What do folks think -- useful trick or too squirrelly to countenance?
Jul 18 '05 #2

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

Similar topics

4
by: Wugi | last post by:
I'm trying to find an equivalent of key-event trapping which is easy in QBasic. Several of my programs build up a geometric figure with two parameter line families, eg with two nested for..next...
15
by: toylet | last post by:
In most perl examples, it used this method to trap error: open(INFILE, $fname) or die "Unable to open $fname"; process_file(); close(INFILE) other_codes(); Now that if I don't want to die...
13
by: Thelma Lubkin | last post by:
I use code extensively; I probably overuse it. But I've been using error trapping very sparingly, and now I've been trapped by that. A form that works for me on the system I'm using, apparently...
2
by: Captain Nemo | last post by:
I'm still using Office 2000 myself, but some of my clients have Office 2003. I've recently added a piece of code to create an instance of Word, open a document, fill in the blanks and become...
5
by: Andreas Beyer | last post by:
There has been quite some traffic about mutable and immutable data types on this list. I understand the issues related to mutable numeric data types. However, in my special case I don't see a...
2
by: Kronalias | last post by:
Hi - could a guru please help? I'm trying to trap errors when I try to load a url into an array. I can trap all errors by using this code: if ( @file($url) == false ){ got a problem; } ...
3
LoanB
by: LoanB | last post by:
Hi I'm looking to ensure that my textbox only accepts numbers .. AND ... mathematical operators + - . / *. an dmaybe a blank space I can ensure that only number are included by using: ...
8
by: Ethan Furman | last post by:
Greetings, List! I'm working on a numeric data type for measured values that will keep track of and limit results to the number of significant digits originally defined for the values in...
0
by: Gabriel Genellina | last post by:
En Thu, 10 Jul 2008 17:37:42 -0300, Ethan Furman <ethan@stoneleaf.us> escribi�: If your objects obey the trichotomy law (an object MUST BE less than, greater than, or equal to another one,...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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...

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.