Skip to content

Instantly share code, notes, and snippets.

@milesrout
Last active August 29, 2015 14:04
Show Gist options
  • Save milesrout/b9d32a273e4728f0df3f to your computer and use it in GitHub Desktop.
Save milesrout/b9d32a273e4728f0df3f to your computer and use it in GitHub Desktop.
struct
def __make_init(*argnames):
def __init__(self, *args):
expected = len(argnames)
actual = len(args)
if expected != actual:
s = '' if expected == 1 else 's'
raise TypeError("__init__() takes exactly {expected} argument{s} ({actual} given)".format(**locals()))
for (arg, argname) in zip(args, argnames):
setattr(self, argname, arg)
return __init__
def __make_str(name, *argnames):
def __str__(self):
arguments = ('{}={}'.format(argname, getattr(self, argname)) for argname in argnames)
return '{}({})'.format(name, ', '.join(arguments))
return __str__
def struct(name, *args):
setattr(__import__('sys').modules[__name__], name, type(name, (), {'__init__' : __make_init(*args), '__str__' : __make_str(name, *args)}))
from struct import struct
struct('Point2D', 'x', 'y')
struct('Point3D', 'x', 'y', 'z')
p1 = Point2D(1, 2)
p2 = Point2D(3, 4)
p3 = Point3D(1, 2, 3)
print(p1)
print(p2)
print(p3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment