On 28 July 2011 18:12, Barry Warsaw <barry@python.org> wrote:
On Jul 27, 2011, at 07:21 PM, Guido van Rossum wrote:

>It's just possible that there's no way to define enums that neither
>introduced a new (class) scope nor requires a lot of redundant typing.

Ezio had a very nice suggestion, which I've implemented in my experimental
branch, e.g.:

   >>> foo = sys.modules['foo']
   >>> Colors.inject(foo)


Why not Colors.inject(__name__)?

This is one line less, the same everywhere, and covers the common case. You could dispatch on string / object if you want to support both.

Michael

 
.inject() takes anything that implements the setattr() protocol.  So that you
could then do:

   >>> import foo
   >>> foo.red
   Colors.red

In my experimental branch I've also made EnumValues subclasses of ints.  This
breaks one test in my Mailman 3 test suite, since I was using a custom encoder
for json.dumps() which knew how to encode EnumValues.  However, the json
module doesn't allow you to override the encoding of basic types, so whereas
before my extended encoder's .default() method got called for all the
EnumValues being encoded in a REST response, they are now encoded
*incorrectly* as their integer values by default.  I'd need to figure out a
workaround for that, but it does show that EnumValue-as-int is a backward
incompatible change.

A few other things I've done in my experimental branch:

- Added an optional argument `iterable` to make_enum() so that you can use the
 convenience function to auto-assign integer values other than sequentially
 incrementing from 1.  E.g.

   >>> def enumiter():
   ...     start = 1
   ...     while True:
   ...         yield start
   ...         start <<= 1
   >>> make_enum('Flags', 'a b c d e f g', enumiter())
   <Flags {a: 1, b: 2, c: 4, d: 8, e: 16, f: 32, g: 64}>

- Renamed attributes .enumclass -> .enum and .enumname -> .name (hey, if
 you're going to be backward incompatible...)

If you want to play with it:

   $ bzr branch lp:~barry/flufl.enum/asint

or take a look at:

   http://bazaar.launchpad.net/~barry/flufl.enum/asint/files

The new using.txt file is at:

   http://tinyurl.com/3s85oq7

Let me know what you think, while I figure out a workaround for the
incompatible change.

Cheers,
-Barry

_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
http://mail.python.org/mailman/listinfo/python-ideas




--
http://www.voidspace.org.uk/

May you do good and not evil
May you find forgiveness for yourself and forgive others
May you share freely, never taking more than you give.
-- the sqlite blessing http://www.sqlite.org/different.html