Skip to content

Instantly share code, notes, and snippets.

@travishen
Last active May 18, 2022 08:36
Show Gist options
  • Save travishen/ac97f317ede4d05397569c3a0b45a678 to your computer and use it in GitHub Desktop.
Save travishen/ac97f317ede4d05397569c3a0b45a678 to your computer and use it in GitHub Desktop.
def record_factory(cls_name, field_names):
try:
field_names = field_names.replace(',', ' ').split()
except AttributeError:
pass
filed_names = tuple(field_names)
def __init__(self, *args, **kwargs):
attrs = dict(zip(self.__slots__, args))
attrs.update(kwargs)
for name, value in attrs.items():
setattr(self, name, value)
def __iter__(self):
# generate attribute value in slots order
for name in self.__slots__:
yield getattr(self, name)
def __repr__(self):
values = ', '.join(f'{name}={value!r}'
for name, value in zip(self.__slots__, self))
cls_name = self.__class__.__name__
return f'{cls_name}({values})'
cls_attrs = dict(__slots__ = field_names,
__init__ = __init__,
__iter__ = __iter__,
__repr__ = __repr__,)
return type(cls_name, (object,), cls_attrs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment