Am I the only one who would love these extentions? - Python 3.0 proposals (long)

Alex Martelli aleax at aleax.it
Tue Nov 11 05:39:32 EST 2003


Alexander Schmolck wrote:
   ...
> IMHO, this is a not such a good way to define enums. Why not do
> 
> AND, ASSERT, BREAK, CLASS, etc == "AND, ASSERT, BREAK, CLASS,
> etc".split(", ")

Unfortunately, this breaks the "once, and only once" principle: you
have to ensure the sequence of words is the same on both sides -- any
error in that respect during maintenance will cause small or big
headaches.

> and you've got the significant advantage that screw-ups are less likely

I disagree with you on this point.  Any time two parts of a program
have to be and remain coordinated during maintenance, screw-ups'
likelihood unfortunately increases.

Keeping enum values in their own namespace (a class or instance) is
also generally preferable to injecting them in global namespace,
IMHO.  If you want each constant's value to be a string, that's easy:

class myenum(Enum):
    AND = ASSERT = BREAK = CLASS = 1

with:

class Enum: __metaclass__ = metaEnum

and:

class metaEnum(type):
    def __new__(mcl, clasname, clasbases, clasdict):
        for k in clasdict:
            clasdict[k] = k
        return type.__new__(mcl, clasname, clasbases, clasdict)

The problem with this is that the attributes' _order_ in the
classbody is lost by the time the metaclass's __new__ runs, as
the class attributes are presented as a dictionary.  But if the
values you want are strings equal to the attributes' names, the
order is not important, so this works fine.

But many applications of enums DO care about order, sigh.


> in combination with iterators).I'd also like to have the apply-* work in
> assignments, e.g. ``first, second, *rest = someList``. This would also
> make python's list destructuring facilities much more powerful.

Yes, I agree on this one.  Further, if the "*rest" was allowed to
receive _any remaining iterable_ (not just necessarily a list, but
rather often an iterator) you'd be able to use itertools.count()
and other unbounded-iterators on the RHS.


Alex





More information about the Python-list mailing list