[Baypiggies] newbie q

K. Richard Pixley rich at noir.com
Wed Nov 25 21:02:11 CET 2009


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


More information about the Baypiggies mailing list