-
-
Save dbl0null/8e76ffe85bb309b1b144866352ee3bea to your computer and use it in GitHub Desktop.
python datatype factory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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