appending to a list via properties

Lonnie Princehouse finite.automaton at gmail.com
Fri Feb 10 16:04:03 EST 2006


Here's a curious hack I want to put up for discussion.  I'm thinking of
writing a PEP for it.

Observation
-----------------
I found myself using this construct for assembling multiple lists:

    foo = []
    qux = []

    while some_condition:
       a, b = calculate_something()
       foo.append(a)
       qux.append(b)

Not elegant!  It requires temporary variables a and b, which are only
used to populate the lists.


Suggestion
----------------

    class better_list (list):
        tail = property(None, list.append)

    foo = better_list()
    qux = better_list()

    while some_condition:
        foo.tail, qux.tail = calculate_something()

Granted, the name tail might not be the best, but you get the idea.


Alternatives
------------------

    1. Use "append" instead, preserving original list.append behavior.

        class better_list (list):
            append = property(lambda l: lambda x: list.append(l,x),
list.append)

    2. Use an external wrapper, similar to operator.*getter

        class propertize (object):
            def __init__(self, target):
                self.__target__ = target
            def __setattr__(self, attribute, value):
                if attribute.startswith('_'): return
object.__setattr__(self, attribute, value)
                else: getattr(self.__target__, attribute)(value)

        propertize(foo).append, propertize(qux).append =
calculate_something()

   
Well?




More information about the Python-list mailing list