This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Enum does not work with reversed
Type: behavior Stage: resolved
Components: Library (Lib) Versions: Python 3.4
process
Status: closed Resolution: fixed
Dependencies: Superseder:
Assigned To: ethan.furman Nosy List: ethan.furman, vajrasky
Priority: normal Keywords: patch

Created on 2013-09-10 09:14 by vajrasky, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Files
File name Uploaded Description Edit
add_reversed_support_for_enum.patch vajrasky, 2013-09-10 09:14 review
add_reversed_support_for_enum_v2.patch vajrasky, 2013-09-12 02:25 review
Messages (5)
msg197428 - (view) Author: Vajrasky Kok (vajrasky) * Date: 2013-09-10 09:14
cutecat@amiau:~/cpython$ cat /tmp/innerplanets.py 
from enum import Enum

class innerplanets(Enum):
    mercury = 1
    venus = 2
    earth = 3
    mars = 4

for planet in innerplanets:
    print(planet)
for planet in reversed(innerplanets):
    print(planet)
cutecat@amiau:~/cpython$ ./python /tmp/innerplanets.py 
innerplanets.mercury
innerplanets.venus
innerplanets.earth
innerplanets.mars
Traceback (most recent call last):
  File "/tmp/innerplanets.py", line 11, in <module>
    for planet in reversed(innerplanets):
  File "/home/cutecat/cpython/Lib/enum.py", line 255, in __getitem__
    return cls._member_map_[name]
KeyError: 3

Attached the patch to add support for reversed in enum.
msg197499 - (view) Author: Ethan Furman (ethan.furman) * (Python committer) Date: 2013-09-11 17:49
Cool, I didn't even know __reversed__ existed!
msg197510 - (view) Author: Vajrasky Kok (vajrasky) * Date: 2013-09-12 02:25
Simplified unit test. I reused enum Season in the test class.

By the way, there is another way to add support for enum without implementing __reversed__ method, which is adding support indexing by number (in __getitem__ method), e.g. Season[1] => Season.SPRING. But I prefer using __reversed__ method.
msg197511 - (view) Author: Ethan Furman (ethan.furman) * (Python committer) Date: 2013-09-12 02:32
Yes, I was aware of that method (not that we would add it that way).  __reversed__ is definitely better for Enum.
msg197741 - (view) Author: Ethan Furman (ethan.furman) * (Python committer) Date: 2013-09-15 01:15
Well, I totally messed up the commit message, but the code is now in place.  Thanks, Vajrasky Kok!
History
Date User Action Args
2022-04-11 14:57:50adminsetgithub: 63195
2013-09-15 01:15:04ethan.furmansetstatus: open -> closed
resolution: fixed
messages: + msg197741

stage: patch review -> resolved
2013-09-12 02:32:42ethan.furmansetmessages: + msg197511
2013-09-12 02:25:36vajraskysetfiles: + add_reversed_support_for_enum_v2.patch

messages: + msg197510
2013-09-11 17:49:03ethan.furmansetassignee: ethan.furman
messages: + msg197499
stage: patch review
2013-09-10 09:14:23vajraskycreate