0

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))
Nineteendo
  • 882
  • 3
  • 18
  • Why do you want to change it into a one liner? Writing different functions for `list`s and `dict`s are better practice than what you are trying to achieve. – BcK Dec 14 '22 at 14:08
  • 1
    Not sure why you want a one-liner or if it's a good idea but I was curious and something like this works as a one-liner `obj[key] = obj[key] and False or value`, pretty ugly... – Iain Shelvington Dec 14 '22 at 14:12
  • Prettier how? Is it like a never-ending prettification? – BcK Dec 14 '22 at 14:19
  • 1
    @Nineteendo I think whatever the solution it's always going to be fairly ugly :) If line length is important then there is also this solution which is slightly smaller - `o[k] = (o[k], v)[1]` – Iain Shelvington Dec 14 '22 at 14:30

1 Answers1

0

That being said, I think this is the most readable solution, which shouldn't be underlined by any interpretor:

def replace(o, k, v):
    try:
        if type(o) == dict and not k in o:
            raise KeyError(k)
        o[k] = v
        print(o)
    except Exception as e:
        print(repr(e))

Let me know if you've a better solution.

Nineteendo
  • 882
  • 3
  • 18