Structures

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Arnaud Delobelle

    #31
    Re: Structures

    Marc 'BlackJack' Rintsch <bj_666@gmx.net writes:
    On Mon, 03 Nov 2008 23:32:25 +0000, Paulo J. Matos wrote:
    >
    >What's then the reason for adding named tuples if they are not
    >mutable...?? ?
    >
    Names are more descriptive than "magic numbers" as indices. See for
    example the "named tuple" returned by `os.stat()`.
    >
    Ciao,
    Marc 'BlackJack' Rintsch
    I'm reminded of a 'struct' decorator I made some time ago:

    def struct(f):
    classname = f.__name__
    prop_names = f.func_code.co_ varnames[:f.func_code.co _argcount]
    def _new(cls, *args, **kwargs):
    return tuple.__new__(c ls, f(*args, **kwargs))
    def _repr(self):
    return '%s%s' % (type(self).__n ame__, tuple(self))
    def prop(i):
    return property(lambda self: self[i])
    attrs = { '__slots__': (), '__new__': _new, '__repr__': _repr }
    attrs.update((n ame, prop(i)) for i, name in enumerate(prop_ names))
    return type(classname, (tuple,), attrs)


    The advantage over namedtuple is that you don't have to repeat the name
    of the structure and you can easily define default values. The drawback
    is that it involved some mild hackery (It won't work as is in Python 3
    as f.func_code changed to f.__code__). It worked like this:
    >>@struct
    .... def Point(x=0, y=0): return float(x), float(y)
    ....
    >>p, q = Point(2, 7), Point(y=3)
    >>p, q
    (Point(2.0, 7.0), Point(0.0, 3.0))
    >>x, y = p
    >>x, y
    (2.0, 7.0)
    >>p.x + p.y
    9.0
    >>p.x = 3
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    AttributeError: can't set attribute
    >>isinstance( p, tuple)
    True

    It's immutable but it would be easy to make it mutable by making it
    inherit from list instead of tuple.

    You could even have some processing:
    >>@struct
    .... def Interval(start, end, size=None):
    .... size = end - start
    .... return start, end, size
    ....
    >>I = Interval(2.5, 6.0)
    >>I.start, I.end, I.size
    (2.5, 6.0, 3.5)

    --
    Arnaud

    Comment

    • Duncan Booth

      #32
      Re: Structures

      Michele Simionato <michele.simion ato@gmail.comwr ote:
      I did not expect such a large difference in instantiation time.
      However I was thinking about
      access time, and then the difference is not impressive (~20-25%):
      >
      The difference in time is because when you create a normal instance Python
      has to create at least two objects: the instance itself, and a dict for its
      attributes. If you use __slots__ for all of the attributes then you no
      longer have a separate __dict__ so you save that extra object creation.

      As soon as you allow other attributes (which happens for example if you
      have a base class without __slots__) I think you'll find the object
      creation time goes back up to normal.

      --
      Duncan Booth http://kupuguy.blogspot.com

      Comment

      • George Sakkis

        #33
        Re: Structures

        On Nov 3, 10:26 pm, Steven D'Aprano <st...@REMOVE-THIS-
        cybersource.com .auwrote:
        On Tue, 04 Nov 2008 00:19:16 +0000, Marc 'BlackJack' Rintsch wrote:
        On Mon, 03 Nov 2008 23:32:25 +0000, Paulo J. Matos wrote:
        >
        What's then the reason for adding named tuples if they are not
        mutable...???
        >
        Names are more descriptive than "magic numbers" as indices.  See for
        example the "named tuple" returned by `os.stat()`.
        >
        I have no objection to named tuples, but I've sometimes
        missed having an equivalent to the Pascal record or C
        struct: essentially a named mutable tuple.
        +1. FWIW, I posted a recipe along these lines, following closely the
        functionality and implementation of namedtuple: http://code.activestate.com/recipes/576555/

        George

        Comment

        Working...