What do you use as symbols for Python ?

Sion Arrowsmith siona at chiark.greenend.org.uk
Fri Nov 11 09:27:44 EST 2005


Gary Herron  <gherron at digipen.edu> wrote:
>Another similar approach that keeps those values together in a single 
>namespace is this (my favorite):
>
>  class State:
>      OPENED, CLOSED, ERROR = range(3)
>
>Then you can refer to the values as
>    State.OPENED
>    State.CLOSED
>    State.ERROR
>
>The extra clarity (and slight wordiness) of the dotted notation seems, 
>somehow, quite Pythonic to me.

I have here an implementation (written by a colleague) of a whole pile
of such -- in this particular case it's helpful to do it in this style
rather than the class OPENED: pass because the values are coming from/
going to a database. And it goes a little further, with

class State:
    Enum = range(3)
    OPENED, CLOSED, ERROR = Enum
    Names = { OPENED: "OPENED", CLOSED: "CLOSED", ERROR: "ERROR" }

so you can used State.Names[state] to provide something user-readable,
and state in State.Enum to check data consistency. (OK, that probably
doesn't make much sense with this particular State, but it does when
your getting value-as-number from an external source.)

-- 
\S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
  ___  |  "Frankly I have no feelings towards penguins one way or the other"
  \X/  |    -- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump



More information about the Python-list mailing list