Skip to content

Instantly share code, notes, and snippets.

@dbl0null
Forked from kwlzn/datatype.py
Created November 30, 2017 10:04
Show Gist options
  • Save dbl0null/8e76ffe85bb309b1b144866352ee3bea to your computer and use it in GitHub Desktop.
Save dbl0null/8e76ffe85bb309b1b144866352ee3bea to your computer and use it in GitHub Desktop.
python datatype factory
#!/usr/bin/env python2.7
import itertools
def datatype(type_name, params):
"""A faster/more efficient namedtuple replacement with better subclassing properties.
>>> RustLibrary = datatype('RustLibrary', ['sources', 'dependencies'])
>>> rl = RustLibrary([1,2,3], [4,5,6])
>>> rl.sources
[1, 2, 3]
>>> rl.dependencies
[4, 5, 6]
>>> isinstance(rl, RustLibrary)
True
"""
class DataType(object):
__slots__ = tuple(params)
def __init__(self, *args):
assert len(args) == len(params), 'invalid number of args'
for kw, v in itertools.izip(params, args):
setattr(self, kw, v)
DataType.__name__ = type_name
return DataType
class SubclassedThing(datatype('Superclass', ['a', 'b', 'c'])):
@property
def product(self):
return self.a * self.b * self.c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment