defstruct.py

Kragen Sitaker kragen at dnaco.net
Tue Oct 16 12:05:31 EDT 2001


# I occasionally find myself writing code like the following:
# class Point:
#     def __init__(self, x, y):
#         self.x = x
#         self.y = y
# and that's the whole class.  This little module lets me write the above code
# as
# Point = defstruct('x', 'y')
# and have done with it.
# 
# The name is taken from Common Lisp; the syntax is taken from MzScheme's
# define-struct and is similar to the Common Lisp boa constructor syntax.
# define-record-type from SRFI 9 is nasty and Scheme-specific enough that
# I didn't use it.
# 
# I hereby dedicate this code to the public domain and disavow any copyright
# interest in it.
# 
# -- Kragen Sitaker, 2001-10-16

def defstruct(*fields):
    class Struct:
        def __init__(self, *contents):
            if len(contents) != len(self.structfields):
                raise TypeError, (
                    "wrong number of arguments: expected %d %s, got %d" %
                    (len(self.structfields),
                     repr(self.structfields),
                     len(contents)))
            for fieldnum in range(len(contents)):
                setattr(self, self.structfields[fieldnum], contents[fieldnum])
    Struct.structfields = fields
    return Struct    
        
def test():
    point = defstruct('x', 'y')
    p1 = point(1, 2)
    assert p1.x == 1
    assert p1.y == 2
    complex = defstruct('real', 'imag')
    assert point is not complex
    assert isinstance(p1, point)
    assert not isinstance(p1, complex)

test()
-- 
<kragen at pobox.com>       Kragen Sitaker     <http://www.pobox.com/~kragen/>
Perilous to all of us are the devices of an art deeper than we possess
ourselves.
       -- Gandalf the White [J.R.R. Tolkien, "The Two Towers", Bk 3, Ch. XI]




More information about the Python-list mailing list