Hi, On Thu, Jun 9, 2011 at 8:06 PM, cool-RR <[email protected]> wrote:
> Hello all, > > A while ago I was introduced to the concept of > enum<http://en.wikipedia.org/wiki/Enumerated_type>in Java. I never programmed > Java, but this looks like > *the* solution for when you want a variable to hold a value from a limited > set of possible values. What is usually done in Python is either using a > string or an index number, both of which are less elegant solutions in my > opinion. > > Python doesn't provide a built-in enum type, but I found a few third-party > modules, out of which I chose `flufl.enum` as being the most promising: > > http://packages.python.org/flufl.enum/docs/using.html#creating-an-enum > > This looks like a pretty good solution. A tad less native than in Java, but > still much better than strings or ints. > If needed I usually do things like: YES, NO, MAYBE = range(3) Can be also simple namespaced under some class: class Should(object): YES, NO, MAYBE = range(3) > > My question is, why do I never see Python code that uses `flufl.enum`, or > any other enum package for that matter? Is there some reason not to use > enums in Python? Perhaps a large portion of Python programmers are ignorant > about enums, (as I was before I saw it recently?) Or perhaps people just > don't really care about making their code elegant? > > Anyway I'll try to start using `flufl.enum` soon. One awesome application > that this could have is to make a Django `EnumField` (or `ChoiceField` or > whatever you want to call it) instead of the current ugly way of making an > `IntegerField` and defining `CHOICES` separately. > IMO it's not suitable for replacing Django's choices. Enums are used in Code/API, but aren't suitable for front-end/UI - where choices come into effect. The display value can, and will, contain spaces, unicode, minus signs, etc, which are problematic in enums. Plus, the displayed values should be translatable. Enums can be used as the values in choices, which is the correct way to use them IMO in such a use case.e:g, taking into account the 1st example: from django.utils.translation import ugettext_lazy as _ SHOULD_CHOICES = ( (YES, _('Yes')), (NO, _('No')), (MAYBE, _('Maybe')), ) And later one can refer to them in the field's choices, model methods/views/etc. Cheers -- Meir
_______________________________________________ Python-il mailing list [email protected] http://hamakor.org.il/cgi-bin/mailman/listinfo/python-il
