Fix Choices docstring, minor code changes:

- remove __getitem__, no need for it anymore
- remove implicit lowercasing (principle of least surprise: strings are usually case sensitive)
This commit is contained in:
Carl Meyer 2010-04-15 22:32:33 -04:00
parent cb46293b0a
commit 02b2082e90
2 changed files with 10 additions and 20 deletions

View file

@ -48,26 +48,25 @@ class Choices(object):
A class to encapsulate handy functionality for lists of choices
for a Django model field.
Accepts verbose choice names as arguments, and automatically
assigns numeric keys to them. When iterated over, behaves as the
standard Django choices tuple of two-tuples.
Accepts as arguments either tuples mapping choice IDs (numeric or
text) to human-readable names, or simply choice IDs (in which case
the ID is also used as the human-readable name). When iterated
over, behaves as the standard Django choices tuple of two-tuples.
Attribute access allows conversion of verbose choice name to
choice key, dictionary access the reverse.
Attribute access allows conversion of choice ID to human-readable
name.
Example:
>>> STATUS = Choices('DRAFT', 'PUBLISHED')
>>> STATUS.draft
DRAFT
>>> STATUS[1]
'PUBLISHED'
>>> tuple(STATUS)
(('DRAFT', 'DRAFT'), ('PUBLISHED', 'PUBLISHED'))
>>> STATUS = Choices(('DRAFT', 'is a draft'), ('PUBLISHED', 'is published'))
>>> STATUS.draft
DRAFT
is a draft
>>> tuple(STATUS)
(('DRAFT', 'is a draft'), ('PUBLISHED', 'is published'))
@ -76,7 +75,7 @@ class Choices(object):
def __init__(self, *choices):
self._choices = tuple(self.equalize(choices))
self._choice_dict = dict(self._choices)
self._reverse_dict = dict(((i[0].lower(), i[0]) for i in self._choices))
self._reverse_dict = dict(((i[0], i[0]) for i in self._choices))
def equalize(self, choices):
for choice in choices:
@ -94,9 +93,6 @@ class Choices(object):
except KeyError:
raise AttributeError(attname)
def __getitem__(self, key):
return self._choices[key][0]
def __repr__(self):
return '%s(%s)' % (self.__class__.__name__,
', '.join(("'%s'" % i[0] for i in self._choices)))

View file

@ -95,17 +95,11 @@ class ChoicesTests(TestCase):
self.STATUS = Choices('DRAFT', 'PUBLISHED')
def test_getattr(self):
self.assertEquals(self.STATUS.draft, 'DRAFT')
def test_getitem(self):
self.assertEquals(self.STATUS[1], 'PUBLISHED')
self.assertEquals(self.STATUS.DRAFT, 'DRAFT')
def test_iteration(self):
self.assertEquals(tuple(self.STATUS), (('DRAFT', 'DRAFT'), ('PUBLISHED', 'PUBLISHED')))
def test_display(self):
self.assertEquals(self.STATUS.draft, 'DRAFT')
class LabelChoicesTests(ChoicesTests):
def setUp(self):
self.STATUS = Choices(
@ -122,7 +116,7 @@ class LabelChoicesTests(ChoicesTests):
)
def test_display(self):
self.assertEquals(self.STATUS.deleted, 'DELETED')
self.assertEquals(self.STATUS.DELETED, 'DELETED')
class InheritanceCastModelTests(TestCase):