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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With