ndanger / pycomparable
- Source
- Commits
- Network (0)
- Issues (0)
- Downloads (0)
- Wiki (1)
- Graphs
-
Branch:
master
pycomparable / README
| ce9b6764 » | ndanger | 2008-10-03 | 1 | ||
| 2 | DISCLAIMER: | ||||
| 3 | |||||
| 4 | Although this works (it really adds the rich comparison operators), it's for | ||||
| 5 | fun/learning purposes only. If you really need all the comparisons, you're | ||||
| 6 | probably better off writing __cmp__. I think Python3000 might automatically | ||||
| 7 | create __ne__ based on __eq__. The one real world use might be to easily | ||||
| 8 | add all rich comparison methods to a subclass where the parent class | ||||
| 9 | implements a subset of the operator. But how often does that happen? Just | ||||
| 10 | use it for fun. | ||||
| 11 | |||||
| 12 | |||||
| 13 | Try to add rich comparison methods (__eq__, __ne__, etc.) to an existing class. | ||||
| 14 | It exports three names: | ||||
| 15 | |||||
| 16 | * comparable - class decorator | ||||
| 17 | * ComparableMetaclass - Metaclass to automatically call comparable | ||||
| 18 | * ComparableMixin - Mixin to automatically call comparable | ||||
| 19 | |||||
| 20 | comparable works as a class decorator. It takes a class as an argument and | ||||
| 21 | returns a decorated class. comparable attempts to add the rich comparison | ||||
| 22 | special methods if they are not defined. If __eq__ is not defined, it will | ||||
| 23 | try to define it as being not != or not (< or >), etc. It then sets != as | ||||
| 24 | the inversion of ==. Finally it sets whatever inequalities are possible | ||||
| 25 | (e.g. < === <= and not ==). | ||||
| 26 | |||||
| 27 | comparable will not overwrite existing methods. | ||||
| 28 | |||||
| 29 | comparable won't add methods if there is not enough information. For | ||||
| 30 | example, if only __eq__ and __ne__ are defined, it will not attempt to add | ||||
| 31 | any inequalities. It also won't raise any errors, so be warned. | ||||
| 32 | |||||
| 33 | ComparableMetaclass and ComparableMixin are additional ways to create a | ||||
| 34 | comparable class. Both are simply wrappers for the main comparable | ||||
| 35 | function. | ||||
| 36 | |||||
| 37 | Inspired by this discussion turned rant on comp.lang.python | ||||
| 38 | (http://groups.google.com/group/comp.lang.python/browse_thread/thread/a5fa8ff0ffadd6ee/1aa3b5d25eae91d5) | ||||
| 39 | Loosely based on Ruby's comparable module | ||||
| 40 | (http://www.ruby-doc.org/core/classes/Comparable.html) though I believe the | ||||
| 41 | implementation is different. | ||||
