Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #106936
| From | jmp <jeanmichel@sequans.com> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: Enum questions. |
| Date | 2016-04-13 13:59 +0200 |
| Message-ID | <mailman.69.1460548765.15650.python-list@python.org> (permalink) |
| References | <570E1B98.4080904@rece.vub.ac.be> <nelcad$puk$1@ger.gmane.org> |
On 04/13/2016 12:12 PM, Antoon Pardon wrote: > I have been looking at the enum documentation and it > seems enums are missing two features I rather find > important. > > 1) Given an Enum value, someway to get the next/previous > one > > 2) Given two Enum values, iterate over the values between > them. > > Did I miss those in the documentation or are they really > missing? > From the doc : "While Enum and IntEnum are expected to cover the majority of use-cases, they cannot cover them all. Here are recipes for some different types of enumerations that can be used directly, or as examples for creating one’s own." I would disagree with you when you state that the features you mentioned are important. They could be useful, in certain cases but most of your code would better be agnostic to the enum value. Now it is possible that you specifically work with a system where those features would be really useful. As mentioned by the documentation, subclassing Enum is possible: tested with python 2.7 from enum import IntEnum class UltimateEnum(IntEnum): @classmethod def range(cls, *args): enumToVal = lambda e: e.value if isinstance(e, cls) else e return (i for i in cls if i.value in range(*map(enumToVal, args))) @property def next(self): it = iter(self.__class__) try: for e in it: if e is self: return next(it) except StopIteration: return None return None class Foo(UltimateEnum): A = 1 B = 4 C = 9 D = 28 print "first to C:" for f in Foo.range(Foo.C): print f print "B to D :" for f in Foo.range(Foo.B, Foo.D): print f print "A to D+1 with step 2 : " for f in Foo.range(Foo.A, Foo.D.value+1, 2): print f print "next property" print Foo.A.next print Foo.C.next print Foo.D.next In [1]: run test.py first to C: Foo.A Foo.B B to D : Foo.B Foo.C A to D+1 with step 2 : Foo.A Foo.C next property Foo.B Foo.D None Hope it helps, jm
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Enum questions. jmp <jeanmichel@sequans.com> - 2016-04-13 13:59 +0200
csiph-web