[Baypiggies] newbie q

Isaac hyperneato at gmail.com
Wed Nov 25 23:10:35 CET 2009


http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python

Hope this helps

On Wed, Nov 25, 2009 at 12:02 PM, K. Richard Pixley <rich at noir.com> wrote:

> Here's a newbie question.
>
> I'm looking to create a collection of opaque types to use as constants,
> akin to enums in C.  I want to be able to compare for equality and inclusion
> in the set.
>
> I've tried using classes & subclasses:
>
> class state(object):
>   class _base(object):
>       def __repr__(self):
>           return '<%s>' % self.__class__
>
>   class up(_base):
>       pass
>
>   class down(_base):
>       pass
>
>   class turned_around(_base):
>       pass
>
> # containment
> isinstance(x, state._base)
>
> # equality
> x == state.up
>
> And I've tried using specific instances:
>
> class state(object):
>   class _base(object):
>      def __init__(self, name):
>           assert isinstance(name, string)
>           self.name = name
>
>       def __repr__(self):
>           return '<%s: %s>' % (self.__class__, self.name)
>
>   up = state('up')
>   down = state('down')
>   turned_around = state('turned_around')
>
> # containment
> isinstance(x, state._base)
>
> # equality
> x == state.up
>
> but neither seems particularly terse, clean, or elegant.  Simple string
> constants and lists are neither opaque nor typed in the sense that to test
> for equality, I'd need to first test for type, (ie, set inclusion), then
> test for equality.
>
> states = ['up', 'down', 'turned_around']
>
> # containment
> x in states
>
> # equality
> x in states and x == 'up'
>
> This is also disappointing because it's impossible to distinguish between
> two different sets of constants.  Eg, I can't distinguish my.up from your.up
> if I'm just using 'up'.
>
> What are other people using?
>
> --rich
> _______________________________________________
> Baypiggies mailing list
> Baypiggies at python.org
> To change your subscription options or unsubscribe:
> http://mail.python.org/mailman/listinfo/baypiggies
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/baypiggies/attachments/20091125/d395495d/attachment.htm>


More information about the Baypiggies mailing list