[Chicago] Ode to <>

Ian Bicking ianb at colorstudy.com
Fri Sep 1 17:39:23 CEST 2006


Brian Ray wrote:
> On Sep 1, 2006, at 10:19 AM, Martin Maney wrote:
> 
>> __eq__(self, other)
> 
> 
> Oh yes, ok, I. Well, Python has me covered.
> 
> But still, I do not see a way to define <>. IMHO, there also should  
> be a way.

__neq__ (not equal).  If you don't define __neq__ it will use "not 
__eq__".  Of course, there's no way to make != and <> act differently.

Note you can also do funny tricks with this stuff, since these methods 
don't have to return True/False.  This is how SQLObject/SQLBuilder 
expressions work (and you can see the same technique elsewhere).  For 
instance:

class Expr(object):
     def __init__(self, expr):
         self.expr = expr
     def __str__(self):
         return self.expr
     def __eq__(self, other):
         return Expr('%s=%s' % (self, other))
     def __neq__(self, other):
         return Expr('%s<>%s' % (self, other))
     def __gt__(self, other):
         return Expr('%s>%s' % (self, other))
     def __getattr__(self, attr):
         return Expr('%s.%s' % (self, attr))
     # and so on...

person = Expr('person')
print person.fname == 'Joe'


-- 
Ian Bicking | ianb at colorstudy.com | http://blog.ianbicking.org


More information about the Chicago mailing list