Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why django uses tuple of tuples to store static dictionaries and should i do the same?

Why django uses tuple of tuples to store for example choices instead of standard dict?

Example:

ORGINAL_MARKET = 1
SECONDARY_MARKET = 2
MARKET_CHOICES = (
     (ORGINAL_MARKET, _('Orginal Market')),
     (SECONDARY_MARKET, _('Secondary Market')),
 )

And should I do it to when I know the dict won't change in time? I reckon the tuples are faster but does it matter if when I try to get value I'm still need to convert it to dict to find it?

UPDATE:

Clarification if I use it as a tuple of tuples I will be getting value using

dict(self.MARKET_CHOICES)[self.ORGINAL_MARKET]

Which will work faster, this or storing values in dict from the beginning?

like image 557
Lord_JABA Avatar asked May 07 '14 12:05

Lord_JABA


Video Answer


1 Answers

The main reason is that ordering is preserved. If you used a dictionary, and called .items() on it to give the choices for a ChoiceField, for example, the ordering of items in the select box would be unreliable when you rendered the form.

If you want the dict, it is easy to create one from the tuple of tuples, the format is already one accepted by the constructer so you can just call dict() on it.

I don't think the immutability is a correct reason - it is not strictly necessary for them to be a tuple of tuples, a list of tuples or even a list of lists would work as well in Django.

like image 147
wim Avatar answered Oct 12 '22 15:10

wim