[Python-Dev] A "record" type (was Re: Py2.6 ideas)

Steven Bethard steven.bethard at gmail.com
Wed Feb 21 19:40:05 CET 2007


On 2/20/07, Steven Bethard <steven.bethard at gmail.com> wrote:
> 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)

Here's a brief comparison between Raymond's NamedTuple factory
(http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/500261) and
my Record class
(http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502237).
Given a ``records`` module containing the recipes and the following
code::

    class RecordPoint(Record):
        __slots__ = 'x', 'y'

    NamedTuplePoint = NamedTuple('NamedTuplePoint x y')

I got the following times from timeit::

$ python -m timeit -s "import records; Point = records.RecordPoint"
"Point(1, 2)"
1000000 loops, best of 3: 0.856 usec per loop
$ python -m timeit -s "import records; Point =
records.NamedTuplePoint" "Point(1, 2)"
1000000 loops, best of 3: 1.59 usec per loop

$ python -m timeit -s "import records; point = records.RecordPoint(1,
2)" "point.x; point.y"
10000000 loops, best of 3: 0.209 usec per loop
$ python -m timeit -s "import records; point =
records.NamedTuplePoint(1, 2)" "point.x; point.y"
1000000 loops, best of 3: 0.551 usec per loop

$ python -m timeit -s "import records; point = records.RecordPoint(1,
2)" "x, y = point"
1000000 loops, best of 3: 1.47 usec per loop
$ python -m timeit -s "import records; point =
records.NamedTuplePoint(1, 2)" "x, y = point"
10000000 loops, best of 3: 0.155 usec per loop

In short, for object construction and attribute access, the Record
class is faster (because __init__ is a simple list of assignments and
attribute access is through C-level slots).  For unpacking and
iteration, the NamedTuple factory is faster (because it's using the
C-level tuple iteration instead of a Python-level generator).

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