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_somet hing()
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_somet hing()
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.*gette r
class propertize (object):
def __init__(self, target):
self.__target__ = target
def __setattr__(sel f, attribute, value):
if attribute.start swith('_'): return
object.__setatt r__(self, attribute, value)
else: getattr(self.__ target__, attribute)(valu e)
propertize(foo) .append, propertize(qux) .append =
calculate_somet hing()
Well?
writing a PEP for it.
Observation
-----------------
I found myself using this construct for assembling multiple lists:
foo = []
qux = []
while some_condition:
a, b = calculate_somet hing()
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_somet hing()
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.*gette r
class propertize (object):
def __init__(self, target):
self.__target__ = target
def __setattr__(sel f, attribute, value):
if attribute.start swith('_'): return
object.__setatt r__(self, attribute, value)
else: getattr(self.__ target__, attribute)(valu e)
propertize(foo) .append, propertize(qux) .append =
calculate_somet hing()
Well?
Comment