For 'nicer' simpler code I was wondering if it were possible to perform a reserved/reflected augmented addition assignment.
[I have checked Stack Overflow for similar questions but cannot find any. So if this is a repeat my apologies, and please may you link the answer.]
For example with a string regular assignment gives:
In[1]: s = 'foo'
In[2]: s += 'bar'
In[3]: print(s)
Out[1]: foobar
But is there any way to do this with a reflected order, without doing s = 'bar' + s
.
So is there any operation similar to something like =+
(which isn't real), such that:
In[1]: s = 'foo'
In[2]: s =+ 'bar'
In[3]: print(s)
Out[1]: barfoo
Thanks in advance for the help :)
This doesn't exist in Python. You can't create a new operator, so it's not something you could implement either. But, there's no problem that can't be solved with yet another level of indirection!
class ReflectedAugmentedAssignableString(object):
def __init__(self, value):
self.value = value
def __iadd__(self, other):
self.value = other + self.value
return self
def __unicode__(self):
return self.value
raastring = ReflectedAugmentedAssignableString("foo")
raastring += "bar"
print(raastring)
>>> "barfoo"
Note: This is terrible ^ , please don't do it.