[Python-Dev] constant/enum type in stdlib

Benjamin Peterson benjamin at python.org
Wed Nov 24 17:32:56 CET 2010


2010/11/24 Steven D'Aprano <steve at pearwood.info>:
> Nick Coghlan wrote:
>>
>> On Wed, Nov 24, 2010 at 10:30 PM, Michael Foord
>> <fuzzyman at 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__.

The construction namespace can be customized, but class.__dict__ must
always be a real dict.



-- 
Regards,
Benjamin


More information about the Python-Dev mailing list