Reputation: 2635
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?
Upvotes: 6
Views: 1007
Reputation: 77339
To be clear: I'm not going to use it in choices=- I'm looking for most efficient method – Lord_JABA
If you want your choices to have a particular order (which often is the case with the choices
parameter) then use tuples, if you don't care use whatever literal you find easier to type (from the allowed datatypes), I doubt you will see any significant difference regarding the memory/cpu footprint for this specific use case.
Upvotes: 0
Reputation: 1807
Tuples are immutable, slightly faster, and Django uses them because they're immutable in the choices
parameter in fields.
If you're using Python 3.4 or later you can use Enums
also which is better than both tuples and dictionaries (but I'm not sure if Django supports them for the choices
parameter).
Upvotes: 0
Reputation: 363183
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.
Upvotes: 6