A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://mail.python.org/pipermail/python-dev/2010-November/105971.html below:

[Python-Dev] constant/enum type in stdlib

[Python-Dev] constant/enum type in stdlibSteven D'Aprano steve at pearwood.info
Wed Nov 24 16:44:57 CET 2010
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__.

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


-- 
Steven

More information about the Python-Dev mailing list

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4