title: How can I elegantly find the next and previous value in a Python Enum?
body: <p>I have a simple enum in Python that looks like this:</p>
  
  <pre><code>from enum import Enum
  
  class MyEnum(Enum):
      #All members have increasing non-consecutive integer values.
      A = 0
      B = 2
      C = 10
      D = 18
      ...
  </code></pre>
  
  <p>I want functions <code>pred()</code> and <code>succ()</code> that given a member of <code>MyEnum</code> return the member of <code>MyEnum</code> that precedes and succeeds the given element, respectively (just like <a href="https://hackage.haskell.org/package/base-4.9.0.0/docs/Prelude.html#t:Enum" rel="noreferrer">the functions of the same name in Haskell</a>). For example <code>succ(MyEnum.B)</code> and <code>pred(MyEnum.D)</code> should both return <code>MyEnum.C</code>. An exception can be raised if <code>succ</code> is called on the last member of <code>pred</code> is called on the first member.</p>
  
  <p>There doesn't seem to be any built in method to do this, and while I can call <code>iter(MyEnum)</code> to iterate over the values it has to go through the whole enum from the beginning. I could probably implement a sloppy loop to accomplish this on my own, but I know there are some real Python gurus on this site, so to you I ask: is there a better approach?</p>