Skip to content

Instantly share code, notes, and snippets.

@wallrj
Created September 29, 2013 19:00
Show Gist options
  • Select an option

  • Save wallrj/6755471 to your computer and use it in GitHub Desktop.

Select an option

Save wallrj/6755471 to your computer and use it in GitHub Desktop.
class ValueConstant(object):
_container = None
_name = None
def __init__(self, value):
self.value = value
def _realize(self, container, name):
self._container = container
self._name = name
def __repr__(self):
return "<%s.%s(%s)>" % (self._container.__name__, self._name, self.value)
class ConstantsContainer(object):
def __init__(self, original):
self.constants = []
self.constantsMap = {}
for k, v in original.__dict__.items():
if isinstance(v, ValueConstant):
v._realize(original, k)
self.constants.append(v)
self.constantsMap[k] = v
self.original = original
def __getattr__(self, name):
return getattr(self.original, name)
def lookupByName(self, name):
return self.constantsMap[name]
def lookupByValue(self, value):
for c in self.constants:
if c.value == value:
return c
def constants(cls):
return ConstantsContainer(cls)
@constants
class RECORDS(object):
A = ValueConstant(1)
NS = ValueConstant(2)
AAAA = ValueConstant(28)
@classmethod
def isHost(cls, constant):
return constant in (cls.A, cls.AAAA)
print RECORDS.A
print RECORDS.AAAA
print RECORDS.constants
print RECORDS.lookupByName("AAAA")
print RECORDS.lookupByValue(28)
print RECORDS.isHost(RECORDS.A)
print RECORDS.isHost(RECORDS.NS)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment