python create empty object of arbitrary type?

1.6k views Asked by At

for types such as list I can readily create an empty list to make this construct work:

 s = []
 s+= [1,2,3]  # result s assigned [1,2,3]

obviously useful in constructs like this:

 s=[]
 for v in (list1,list2,list3..):
   if condition : s+=v

Now I'm working with a user defined type, defined in a module that I cannot read or change.. I have to do this:

 s=0
 for v in (typefoo1,typefoo2,..):
   if condition :
    if s==0 :
     s=v
    else:
     s+=v

This works, but is ugly and occurs so often it is pretty annoying. so.. is there a way to create an empty object such that the += operator would behave simply like a regular assignment= regardless of the type on the r.h.s?

Edit: I tried to keep the question generic deliberately, but for completeness the type in question is an Abaqus geometry sequence.

2

There are 2 answers

0
Kevin On BEST ANSWER

is there a way to create an empty object such that the += operator would behave simply like a regular assignment = regardless of the type on the r.h.s?

Sure. Just write a class and define your __add__ method to return the RHS unmodified.

class DummyItem:
    def __add__(self, other):
        return other

s = DummyItem()
s += 23
print s

Result:

23
3
tobias_k On

Assuming that your list has at least one element, you could just create an iterator and use next to get the first element and them sum the rest:

i = iter(lst)
s = next(i)
for x in i:
    s += x

You could also do this using the sum function, with a second paramter specifying the initial value: s = sum(i, next(i)). This explicitly does not work for strings, but you could also use reduce in a similar way, which will work with strings: s = reduce(operator.add, i, next(i)). Or, you could even combine this with the DummyItem from @Kevin's answer, as s = sum(lst, DummyItem()). This way it also works with strings, and you can use the list directly and do not need to create an iterator.