[Python-Dev] constant/enum type in stdlib (original) (raw)
Ron Adam rrr at ronadam.com
Tue Nov 23 22:21:17 CET 2010
- Previous message: [Python-Dev] constant/enum type in stdlib
- Next message: [Python-Dev] constant/enum type in stdlib
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Oops.. x2 should have been 2x below.
On 11/23/2010 03:03 PM, Ron Adam wrote:
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]
[2**x for x in range(10)] [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
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 at python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/python-python-dev%40m.gmane.org
- Previous message: [Python-Dev] constant/enum type in stdlib
- Next message: [Python-Dev] constant/enum type in stdlib
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]