[pypy-dev] Avoiding code duplication

Antonio Cuni anto.cuni at gmail.com
Fri Apr 14 16:53:28 CEST 2006


Hi all,
in these days I'm completing the implementation of 
ootypesystem/rlist.py, but I've found that often I have to write code 
very similar to those in lltypesystem/rlist.py.

Let's explain by an example; consider the ll_listindex function in both 
files:

# lltypesystem
def ll_listindex(lst, obj, eqfn):
     items = lst.ll_items()
     lng = lst.ll_length()
     j = 0
     while j < lng:
         if eqfn is None:
             if items[j] == obj:
                 return j
         else:
             if eqfn(items[j], obj):
                 return j
         j += 1
     raise ValueError # can't say 'list.index(x): x not in list'


# ootypesystem
def ll_listindex(lst, obj, eqfn):
     lng = lst.length()
     j = 0
     while j < lng:
         if eqfn is None:
             if lst.getitem_nonneg(j) == obj:
                 return j
         else:
             if eqfn(lst.getitem_nonneg(j), obj):
                 return j
         j += 1
     raise ValueError # can't say 'list.index(x): x not in list'

As you can see they are quite similar, but I can't find an elegant way 
to merge them. There are two problems:
   1) the names of some methods don't match (e.g., ll_length vs. length
   2) the setitem/getitem interface is very different

The first problem is easy to solve; it should be sufficient to rename 
the methods in ootype.List._GENERIC_METHODS.

The same isn't true for the second problem; one possibility could be to 
pass some dummy placeholder as argument in the same style of 
dum_checkidx/dum_nocheck, but I guess the code will became a nightmare.

Another solution could be to add an extra level of indirection but I 
guess this could bring to some efficiency penalty.

Any idea?

ciao Anto



More information about the Pypy-dev mailing list