From 5317df06358371b6dbbbbf48f25679e23b9be8ae Mon Sep 17 00:00:00 2001 From: James Turk Date: Sun, 27 Mar 2011 13:30:13 -0400 Subject: [PATCH] CEnum --- TODO | 1 - csdl/__init__.py | 3 ++- csdl/enum.py | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+), 2 deletions(-) create mode 100644 csdl/enum.py diff --git a/TODO b/TODO index 9d00064..a76d763 100644 --- a/TODO +++ b/TODO @@ -1,5 +1,4 @@ Someday - * Event Support * have Window pass-through to Renderer Maybe diff --git a/csdl/__init__.py b/csdl/__init__.py index 23c8ff1..1e003b0 100644 --- a/csdl/__init__.py +++ b/csdl/__init__.py @@ -1,8 +1,9 @@ import ctypes from .internal import _SDL, errcheck, Version +from enum import CEnum # Constants -class INIT(object): +class INIT(CEnum): TIMER = 0x00000001 AUDIO = 0x00000010 VIDEO = 0x00000020 diff --git a/csdl/enum.py b/csdl/enum.py new file mode 100644 index 0000000..abcc8ef --- /dev/null +++ b/csdl/enum.py @@ -0,0 +1,46 @@ +""" CEnum & supporting classes, based on idea from Mike Bayer + see http://techspot.zzzeek.org/2011/01/14/the-enum-recipe/ +""" + +class CEnumSymbol(int): + def __new__(cls, name, value, description, **kwargs): + val = super(CEnumSymbol, cls).__new__(cls, value) + val.name = name + val.description = description + return val + + def __repr__(self): + return "<%s>" % self.name + +class CEnumMeta(type): + def __init__(cls, classname, bases, dict_): + cls._reg = reg = cls._reg.copy() + for k, v in dict_.items(): + if isinstance(v, tuple): + sym = reg[v[0]] = CEnumSymbol(k, *v) + setattr(cls, k, sym) + elif isinstance(v, int): + sym = reg[v] = CEnumSymbol(k, v, k) + setattr(cls, k, sym) + return type.__init__(cls, classname, bases, dict_) + + def __iter__(cls): + return iter(cls._reg.values()) + +class CEnum(object): + __metaclass__ = CEnumMeta + _reg = {} + + @classmethod + def from_int(cls, value): + try: + return cls._reg[value] + except KeyError: + raise ValueError( + "Invalid value for %r: %r" % + (cls.__name__, value) + ) + + @classmethod + def values(cls): + return cls._reg.keys()