Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

A += operator that works for both strings and ints

Is there a way in Python to initialize a variable so that it will work with += "a string" or with += 100?
For example:

a = <what to put here>
a += 100 # a = 100
b=<same what to put here from above>  
b+="a string" # b = "a string"

If I use:

a = ""
a += "a string" # this will work fine
b = ""
b += 0 # -> TypeError

Once the type of the variable has been defined, it is okay to get a TypeError afterwards if I try to += a different type. For example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

a = <what to put here>
a += "a string" # a = "a string"
a += 200 # -> okay to get a TypeError here

I’m only interested in making this work for ints and strings.

>Solution :

a = type('', (), {'__add__': lambda _, x: x})()
a += 100

b = type('', (), {'__add__': lambda _, x: x})()  
b += "a string"

print([a, b])

Output (Attempt This Online!):

[100, 'a string']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading