[Python-Dev] A "record" type (was Re: Py2.6 ideas)
Steven Bethard
steven.bethard at gmail.com
Wed Feb 21 00:16:31 CET 2007
On 2/20/07, Larry Hastings <larry at hastings.org> wrote:
> # the easy way to define a "subclass" of record
> def Point(x, y):
> return record(x = x, y = y)
>
> # you can use hack-y features to make your "subclasses" more swell
> def Point(x, y):
> x = record(x = x, y = y)
> # a hack to print the name "Point" instead of "record"
> x.__classname__ = "Point"
> # a hack to impose an ordering on the repr() display
> x.__names__ = ("x", "y")
> return x
>
> p = Point(3, 5)
> q = Point(2, y=5)
> r = Point(y=2, x=4)
> print p, q, r
>
> # test pickling
> import pickle
> pikl = pickle.dumps(p)
> pp = pickle.loads(pikl)
> print pp
> print pp == p
>
> # test that the output repr works to construct
> s = repr(p)
> print repr(s)
> peval = eval(s)
> print peval
> print p == peval
> ------
>
> Yeah, I considered using __slots__, but that was gonna take too long.
Here's a simple implementation using __slots__:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502237
And you don't have to hack anything to get good help() and a nice
repr(). Declare a simple class for your type and you're ready to go::
>>> class Point(Record):
... __slots__ = 'x', 'y'
...
>>> Point(3, 4)
Point(x=3, y=4)
STeVe
--
I'm not *in*-sane. Indeed, I am so far *out* of sane that you appear a
tiny blip on the distant coast of sanity.
--- Bucky Katt, Get Fuzzy
More information about the Python-Dev
mailing list