[Python-Dev] constant/enum type in stdlib
Ben.Cottrell at nominum.com
Ben.Cottrell at nominum.com
Tue Nov 23 16:37:43 CET 2010
On Tue, 23 Nov 2010 15:15:29 +0000, Michael Foord wrote:
> There are still two reasonable APIs (unless you have changed your mind
> and think that sticking with plain integers is best), of which I prefer
> the latter:
>
> SOME_CONST = Constant('SOME_CONST', 1)
> OTHER_CONST = Constant('OTHER_CONST', 2)
>
> or:
>
> Constants = make_constants('Constants', 'SOME_CONST OTHER_CONST', start=1)
> SOME_CONST = Constants.SOME_CONST
> OTHER_CONST = Constants.OTHER_CONST
I prefer the latter too, because that makes it possible to have
'Constants' be a rendezvous point for making sure that you're
passing something valid. Perhaps using 'in':
def func(foo):
if foo not in Constants:
raise ValueError('foo must be SOME_CONST or OTHER_CONST')
...
I know this is probably not going to happen, but I would *so much*
like it if functions would start rejecting "the wrong kind of 2".
Constants that are valid, integer-wise, but which aren't part of
the set of constants allowed for that argument. I'd prefer not to
think of the number of times I've made the following mistake:
s = socket.socket(socket.SOCK_DGRAM, socket.AF_INET)
~Ben
More information about the Python-Dev
mailing list