[Python-Dev] constant/enum type in stdlib (original) (raw)

Michael Foord fuzzyman at voidspace.org.uk
Tue Nov 23 17:19:16 CET 2010


On 23/11/2010 15:37, Ben.Cottrell at nominum.com wrote:

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:

SOMECONST = Constant('SOMECONST', 1) OTHERCONST = Constant('OTHERCONST', 2) or: Constants = makeconstants('Constants', 'SOMECONST OTHERCONST', start=1) SOMECONST = Constants.SOMECONST OTHERCONST = Constants.OTHERCONST 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 SOMECONST or OTHERCONST') ... 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.SOCKDGRAM, socket.AFINET)

Well it would be perfectly possible for the contains method (on the metaclass so that a Constants class can act as a container) to permit a raw integer (to be backwards compatible with code using hard coded values) but not permit other constants that aren't valid. Code that is deliberately using the wrong constants would be screwed of course...

All the best,

Michael

~Ben


Python-Dev mailing list Python-Dev at python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/fuzzyman%40voidspace.org.uk

--

http://www.voidspace.org.uk/

READ CAREFULLY. By accepting and reading this email you agree, on behalf of your employer, to release me from all obligations and waivers arising from any and all NON-NEGOTIATED agreements, licenses, terms-of-service, shrinkwrap, clickwrap, browsewrap, confidentiality, non-disclosure, non-compete and acceptable use policies (”BOGUS AGREEMENTS”) that I have entered into with your employer, its partners, licensors, agents and assigns, in perpetuity, without prejudice to my ongoing rights and privileges. You further represent that you have the authority to release me from any BOGUS AGREEMENTS on behalf of your employer.



More information about the Python-Dev mailing list