יום שלישי, 29 באפריל 2014

functools.total_ordering

Example of using the  @functools.total_ordering (based on the sample from http://pymotw.com/2/functools/)

import functools
import inspect
from pprint import pprint
@functools.total_ordering
class MyObject(object):
    def __init__(self, val):
        self.val = val
    def __eq__(self, other):
        print ('  testing __eq__(%s, %s)' % (self.val, other.val))
        return len ( self.val)  == len ( other.val)
    def __gt__(self, other):
        print ('  testing __gt__(%s, %s)' % (self.val, other.val))
        return len (self.val) > len (other.val)
    def TestMethod(self):
        pass
print ('Methods:\n')
pprint(inspect.getmembers(MyObject))
a = MyObject("Long name bla bal ")
b = MyObject("Short mame")
print ('\nComparisons:')
for expr in [ 'a < b','a > b', 'a <= b', 'a == b', 'a >= b' ]:
    print ('\n%-6s:' % expr)
    result = eval(expr)
    print ('  result of %s: %s' % (expr, result))

The Result:
Methods:
[('TestMethod', <function MyObject.TestMethod at 0x03146270>),
('__class__', <class 'type'>),
('__delattr__', <slot wrapper '__delattr__' of 'object' objects>),
('__dict__',
  mappingproxy({'__module__': '__main__', '__le__': <function total_ordering.<locals>.<lambda> at 0x031464B0>, '__dict__': <attribute '__dict__' of 'MyObject' objects>, '__eq__': <function MyObject.__eq__ at 0x031461E0>, '__doc__': None, '__hash__': None, '__lt__': <function total_ordering.<locals>.<lambda> at 0x03146420>, '__gt__': <function MyObject.__gt__ at 0x03146228>, '__init__': <function MyObject.__init__ at 0x03132A08>, 'TestMethod': <function MyObject.TestMethod at 0x03146270>, '__weakref__': <attribute '__weakref__' of 'MyObject' objects>, '__ge__': <function total_ordering.<locals>.<lambda> at 0x03146468>})),
('__dir__', <method '__dir__' of 'object' objects>),
('__doc__', None),
('__eq__', <function MyObject.__eq__ at 0x031461E0>),
('__format__', <method '__format__' of 'object' objects>),
('__ge__', <function total_ordering.<locals>.<lambda> at 0x03146468>),
('__getattribute__', <slot wrapper '__getattribute__' of 'object' objects>),
('__gt__', <function MyObject.__gt__ at 0x03146228>),
('__hash__', None),
('__init__', <function MyObject.__init__ at 0x03132A08>),
('__le__', <function total_ordering.<locals>.<lambda> at 0x031464B0>),
('__lt__', <function total_ordering.<locals>.<lambda> at 0x03146420>),
('__module__', '__main__'),
('__ne__', <slot wrapper '__ne__' of 'object' objects>),
('__new__', <built-in method __new__ of type object at 0x5E774EA8>),
('__reduce__', <method '__reduce__' of 'object' objects>),
('__reduce_ex__', <method '__reduce_ex__' of 'object' objects>),
('__repr__', <slot wrapper '__repr__' of 'object' objects>),
('__setattr__', <slot wrapper '__setattr__' of 'object' objects>),
('__sizeof__', <method '__sizeof__' of 'object' objects>),
('__str__', <slot wrapper '__str__' of 'object' objects>),
('__subclasshook__',
  <built-in method __subclasshook__ of type object at 0x03135E30>),
('__weakref__', <attribute '__weakref__' of 'MyObject' objects>)]


Comparisons:
a < b :


  testing __gt__(Long name bla bal , Short mame)


  result of a < b: False


a > b :


  testing __gt__(Long name bla bal , Short mame)


  result of a > b: True


a <= b:


  testing __gt__(Long name bla bal , Short mame)


  result of a <= b: False


a == b:


  testing __eq__(Long name bla bal , Short mame)


  result of a == b: False


a >= b:


  testing __gt__(Long name bla bal , Short mame)


  result of a >= b: True

Notes
1.The @functools.total_ordering annotation add implementation of the <= and the => compressions sign  based on the gt and eq methods (without the annotation an exception will be raised ) .
2.The pretty print module handle the iterable collection printing (adding the line feed and cr after printing each member of the list)
3.The inspect module is responsible for getting classes meta data .
4.The  __gt__ and the   __eq__ must be override when using  @functools.total_ordering

אין תגובות:

הוסף רשומת תגובה