0

I am doing something like this and it works but I am not sure if it is the right way to do it. When there is an exception in one of the case methods the trace stops at the line containing }["case1"]("name"). But the reason for the error is correct like if I was expecting a dict and passed a list I will get a list is unhashable exception but on }["case1"]("name") not in the method where that is happening it will stop the traceback here. So if this goes a few levels deep debugging it can become... tricky.

def test(what, data):
    def case1(data):
        # do something with data
        result =  "Hello " + data
        return result

    def case2(data):
        # do something with data
        result = "bye " + foo 
        return result
    res = {
        "case1": case1,
        "case2": case2
    }[what](data)
    print(res)

test("case1", "Foo")

1 Answer 1

1

Separate the dict definition and the call, and you'll be fine:

def test(what, data):
    def case1(data):
        # do something with data
        result =  "Hello " + data
        return result

    def case2(data):
        # do something with data
        result = "bye " + foo 
        return result
    res = {
        "case1": case1,
        "case2": case2
    }
    print(res[what](data))

test("case1", "Foo")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.