0

I have this list of errors with their associated codes and descriptions:

Exception = namedtuple("Exception", "code name description")
exceptions = [
    Exception(1, "ILLEGAL FUNCTION", "Definition 1"),
    Exception(2, "ILLEGAL DATA ADDRESS", "Definition 2"),
    Exception(3, "ILLEGAL DATA VALUE", "Definition 2")
]

I would like a function that retrieves the exception with code==exception_code. I've searched around and the closest I could come up with is this:

# Returns the Exception tuple corresponding to the exception_code
def getException(self):
    return [item for item in exceptions if item[0] == self.exception_code]

This works but it's actually returning a list. My experience with Python is quite poor and I can't figure out how to simply return the tuple instead

NB: There will always be exactly one tuple with code == exception_code

Sample output of print x.getException with my current getException:

[Exception(code=2, name='ILLEGAL DATA ADDRESS', description='Definition 2')]
2
  • Why not use a dictionary instead? Commented Oct 3, 2014 at 17:54
  • What? What use would that be? Also, if you don't want a list, why use a list comprehension? Commented Oct 3, 2014 at 17:57

1 Answer 1

3

In that case, you're better off making exceptions a dict:

exceptions = {
    1: Exception(1, "ILLEGAL FUNCTION", "Definition 1"),
    2: Exception(2, "ILLEGAL DATA ADDRESS", "Definition 2"),
    3: Exception(3, "ILLEGAL DATA VALUE", "Definition 2")
}

From here, your getException function becomes trivial:

def getException(code):
    return exceptions[code]

... and you have to wonder whether the function call looks better than just inlining :-)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this looks much better, will try it out and give you the point

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.