Appending to []
Kiuhnm
kiuhnm03.4t.yahoo.it
Sun Apr 22 08:15:21 EDT 2012
On 4/22/2012 10:29, Bernd Nawothnig wrote:
[...]
> In general I always prefer the pure functional approach. But you are
> right, if it is too costly, one has to weigh the pros and contras.
Here's some stupid trick I came up with after reading this thread. It's
of very limited use, of course and I don't even know whether it's
reliable or not.
-->
import sys
class MyList: # just a test
def __init__(self, iter):
self.__start_cnt = sys.getrefcount(self)
self.__elems = list(iter)
def __add__(self, other):
global optimizations
cnt = sys.getrefcount(self)
if cnt == self.__start_cnt and len(self.__elems) > 100:
print('optimized')
optimizations += 1
self.__elems.extend(other.__elems)
return self
print('normal behavior')
return MyList(self.__elems + other.__elems)
def __eq__(self, other):
return self.__elems == other.__elems
def __iter__(self):
return self.__elems.__iter__()
optimizations = 0
print('#1')
y = MyList([1000, 1001])
x = MyList(range(0, 1000)) + y
assert x == MyList(range(0, 1002))
assert optimizations == 1
optimizations = 0
print('#2')
x = MyList(range(0, 1000))
z = x + MyList([1000, 1001])
assert x == MyList(range(0, 1000))
assert z == MyList(range(0, 1002))
assert optimizations == 0
optimizations = 0
print('#3')
def comp_list(from_, to_):
# Some long computation which results in a list.
return MyList(range(from_, to_))
x = comp_list(0, 1000) + comp_list(1000, 2000) + MyList([2000, 2001])
assert x == MyList(range(0, 2002))
assert optimizations == 2
<--
Kiuhnm
More information about the Python-list
mailing list