appending to a list via properties
Larry Bates
larry.bates at websafe.com
Fri Feb 10 18:23:25 EST 2006
Lonnie Princehouse wrote:
> 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?
>
Not entirely sure I understand, but here goes. I normally
use list comprehensions. I'm assuming that calculate_something()
is acting on a list of items. If not then maybe some underlying
data refactoring is in order. If so you write:
results=[calculate_something(x) for x in list_of_items]
foo=result[x[0] for x in results]
qux=result[x[1] for x in results]
Without knowing more about what calculate_something() does
and what condition terminates the loop it is hard to say if
this will work for you.
-Larry Bates
More information about the Python-list
mailing list