On 11/23/2010 12:07 PM, Antoine Pitrou wrote:
Le mardi 23 novembre 2010 à 12:50 -0500, Isaac Morland a écrit :
Each enumeration is a type (well, OK, not in every language, presumably,
but certainly in many languages).  The word "basic" is more important than
"types" in my sentence - the point is that an enumeration capability is a
very common one in a type system, and is very general, not specific to any
particular application.

Python already has an enumeration capability. It's called range().
There's nothing else that C enums have. AFAICT, neither do enums in
other mainstream languages (assuming they even exist; I don't remember
Perl, PHP or Javascript having anything like that, but perhaps I'm
mistaken).


Aren't we forgetting enumerate?

>>> colors = 'BLACK BROWN RED ORANGE YELLOW GREEN BLUE VIOLET GREY WHITE'

>>> dict(e for e in enumerate(colors.split()))
{0: 'BLACK', 1: 'BROWN', 2: 'RED', 3: 'ORANGE', 4: 'YELLOW', 5: 'GREEN', 6: 'BLUE', 7: 'VIOLET', 8: 'GREY', 9: 'WHITE'}

>>> dict((f, n) for (n, f) in enumerate(colors.split()))
{'BLUE': 6, 'BROWN': 1, 'GREY': 8, 'YELLOW': 4, 'GREEN': 5, 'VIOLET': 7, 'ORANGE': 3, 'BLACK': 0, 'WHITE': 9, 'RED': 2}


Most other languages that use numbered constants number them by base n^2.

>>> [x**2 for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]


Binary flags have the advantage of saving memory because you can assign more than one to a single integer. Another advantage is other languages use them so it can make it easier interface with them. There also may be some performance advantages as well since you can test for multiple flags with a single comparison.

Sets of strings can also work when you don't need to associate a numeric value to the constant. ie... the constant is the value. In this case the set supplies the api.

Cheers,
  Ron

_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to