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_oper ators, 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(ty pe):
def __new__(cls, classname, bases, classdict):
fnDict = classdict['implements_ope rators']
for fn in fnDict.iterkeys ():
for magicName in fnDict[fn]:
for opName in (magicName, '__%s'%magicNam e[3:]):
# try magicName else assume in-place/right
# and strip out the presumptive 'i'/'r'
try:
op = getattr(operato r, 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__(cl s, 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_oper ators = {
binop: ('__add__','__s ub__','__mul__' ,'__div__'),
ibinop: ('__iadd__','__ isub__','__imul __','__idiv__') ,
unop: ('__neg__','__p os__','__abs__' ,'__invert__'),
} 1 1419
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? This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 loops; after that, the
process is redone, or moves on to a new position of the same figure. With a
slow system each build-up may take some time. But after, say the inner
for...next loop it's easy to scan for a key-event with an a$=inkey$ command...
|
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 after the open so as to run
other_codes()? Could I test the value of file handle INFILE like what I
did with C?
|
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 runs into
problems on the system where it will actually be used, and since I
used so little error-trapping it dies very ungracefully.
I will of course try to fix whatever is causing the error and add
error-trapping to the functions where the...
|
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 visible so the document can be
printed and/or modified.
This all takes place within one form, in which the Word.Application and
Word.Document objects are both private form-level variables. Just to be on
the safe side I included this piece of code in...
|
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 better solution to the
problem.
Here is what I am doing:
I am using a third party library that is performing basic numerical
operations (adding, multiplying, etc.) with objects of unknown type. Of
course, the objects must support the numerical...
| |
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;
}
.... but then I don't know whether the problem is that the url file
|
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:
private void txtSurname_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.Handled = !(Char.IsDigit(e.KeyChar)))
{
|
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 question.
I am doing this primarily because I enjoy playing with numbers, and also
to get some experience with unit testing.
At this point I have the __init__ portion finished, and am starting on
|
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, and there is no other possibility)
then __cmp__ is enough, and easier to define than all the rich comparison
operations.
In other cases, __cmp__ is not suitable: by example, complex numbers can't
define "greater than" ; you can only use "equal" or...
|
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...
|
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,...
| |
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...
|
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,...
|
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...
|
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();...
|
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: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |