Search code examples
pythonabaqus

python create empty object of arbitrary type?


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.


Solution

  • 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