RecordConstructorInfo for python

This commit is contained in:
Tony Garnock-Jones 2018-11-19 16:55:22 +00:00
parent 594b379a77
commit 87deddc879
1 changed files with 38 additions and 0 deletions

View File

@ -75,6 +75,44 @@ class Record(object):
for f in self.fields:
encoder.append(f)
@staticmethod
def makeConstructor(labelSymbolText, fieldNames):
return Record.makeBasicConstructor(Symbol(labelSymbolText), fieldNames)
@staticmethod
def makeBasicConstructor(label, fieldNames):
if type(fieldNames) == str:
fieldNames = fieldNames.split()
arity = len(fieldNames)
def ctor(*fields):
if len(fields) != arity:
raise Exception("Record: cannot instantiate %r expecting %d fields with %d fields"%(
label,
arity,
len(fields)))
return Record(label, fields)
ctor.constructorInfo = RecordConstructorInfo(label, arity)
ctor.isClassOf = lambda v: \
isinstance(v, Record) and v.key == label and len(v.fields) == arity
return ctor
class RecordConstructorInfo(object):
def __init__(self, key, arity):
self.key = key
self.arity = arity
def __eq__(self, other):
return isinstance(other, RecordConstructorInfo) and \
(self.key, self.arity) == (other.key, other.arity)
def __hash__(self):
if self.__hash is None:
self.__hash = hash((self.key, self.arity))
return self.__hash
def __repr__(self):
return str(self.key) + '/' + str(self.arity)
# Blub blub blub
class ImmutableDict(dict):
def __init__(self, *args, **kwargs):