The below is a class designed to implement Rememember the Milk's task priorities. I'm using it partly as an exercise in "Pythonic" programming, so it's fairly simple already, but advice on how to make it simpler or more Pythonic would be particularly appreciated.
I'm using Python 2.6.5 in case it makes any difference.
class Pri(int): # Subclass int to get handy comparison functions etc.
'''Task priority'''
public_from_internal = {1: 1, 2: 2, 3: 3, 4: 'N'}
internal_from_public_str = {'N': 4, '1': 1, '2': 2, '3': 3}
_dict = dict()
def __new__(cls, level):
try:
level = Pri.internal_from_public_str[str(level)]
except KeyError:
raise ValueError, "Pri must be 'N', '1', '2', or '3'"
# If there's already an instance of this priority, don't create a new one.
if level in Pri._dict: return Pri._dict[level]
else: return super(Pri, cls).__new__(cls, level)
def __init__(self, level):
super(Pri, self).__init__()
Pri._dict[self] = self
def __repr__(self): return "Pri('" + str(Pri.public_from_internal[self]) + "')"
# Priority 1 is clearly greater than priority 3, so invert cmp
def __cmp__(self, other): return (-cmp(int(self), int(other)))
Some selected output, for the curious:
>>> Pri(1)
Pri('1')
>>> Pri('N')
Pri('N')
>>> Pri(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "rtm.py", line 10, in __new__
raise ValueError, "Pri must be 'N', '1', '2', or '3'"
ValueError: Pri must be 'N', '1', '2', or '3'
>>> Pri._dict
{Pri('1'): Pri('1'), Pri('N'): Pri('N')}
>>> Pri(1) > Pri(2)
True
>>> bool(Pri('N'))
True
>>> repr(Pri("2"))
"Pri('2')"
>>> print repr(Pri('N'))
Pri('N')
>>> Pri(1)._dict
{Pri('1'): Pri('1'), Pri('2'): Pri('2'), Pri('N'): Pri('N')}
int
-- I don't see any benefit from it here. Maybe I missed something? – Matt Fenwick Nov 23 '11 at 19:22