1

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 :)

Aldahunter
  • 618
  • 1
  • 6
  • 12

1 Answers1

1

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.

munk
  • 12,340
  • 8
  • 51
  • 71
  • A shame this isn't implemented in the language and thank you for the 'hack'! Why is this considered terrible? – Aldahunter Apr 17 '19 at 01:39
  • 1
    This is terrible because it's unexpected. With python, the rule is to prefer one way of doing something and that thing should be obvious. If you have a good reason to prefer this approach, or it's for a personal project nobody else will work on, that's one thing, but if it's a shared codebase, then it's important to consider the impact of readability vs what you get from this "feature". – munk Apr 17 '19 at 15:01
  • Yes that makes sense, I wasn't thinking about others since this if for a personal project (for the best since I'm sure others would hate my code practise ahah). Thank you! – Aldahunter Apr 17 '19 at 19:05