Can this behaviour be replicated using a cleaner solution? I would prefer a pretty one-liner, but that might not be possible.
Wrapping this wrapper doesn't count
The program MUST give an error when the key or index doesn't exist.
def replace(obj, key, value):
try:
obj[key] # assure existance
obj[key] = value
print(obj)
except Exception as e:
print(repr(e))
replace([0], 0, 1)
replace({"a": 0}, "a", 1)
replace([], 0, 1)
replace({}, "a", 1)
Output:
[1]
{'a': 1}
IndexError('list index out of range')
KeyError('a')
I currently have this thanks to @Iain Shelvington:
def replace(o, k, v):
try:
o[k] = o[k] and False or v
print(o)
except Exception as e:
print(repr(e))
And this other hacky solution, which is only technically smaller:
def replace(o, k, v):
try:
o[k] = v if o[k] else v
print(o)
except Exception as e:
print(repr(e))
This one after the suggestion to work with tuples, which is actually OK.
def replace(o, k, v):
try:
o[k], _ = v, o[k]
print(o)
except Exception as e:
print(repr(e))
And this cheat:
def replace(o, k, v):
try:
o[k]; o[k] = v
print(o)
except Exception as e:
print(repr(e))