Nick Coghlan wrote:
On Wed, Nov 24, 2010 at 10:30 PM, Michael Foord
<fuzzy...@voidspace.org.uk> wrote:
Based on a non-exhaustive search, Python standard library modules currently
using integers for constants:

Thanks for that review. I think following up on the "NamedConstant"
idea may make more sense than pursuing enums in their own right.

Pardon me if I've missed something in this thread, but when you say "NamedConstant", do you mean actual constants that can only be bound once but not re-bound? If so, +1. If not, what do you mean?

I thought PEP 3115 could be used to implement such constants, but I can't get it to work...

class readonlydict(dict):
    def __setitem__(self, key, value):
        if key in self:
            raise TypeError("can't rebind constant")
        dict.__setitem__(self, key, value)
    # Need to also handle updates, del, pop, etc.

class MetaConstant(type):
    @classmethod
    def __prepare__(metacls, name, bases):
        return readonlydict()
    def __new__(cls, name, bases, classdict):
        assert type(classdict) is readonlydict
        return type.__new__(cls, name, bases, classdict)

class Constant(metaclass=MetaConstant):
    a = 1
    b = 2
    c = 3


What I expect is that Constant.a should return 1, and Constant.a=2 should raise TypeError, but what I get is a normal class __dict__.

>>> Constant.a
1
>>> Constant.a = 2
>>> Constant.a
2


--
Steven

_______________________________________________
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