Reputation: 12520
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')]
Upvotes: 0
Views: 653
Reputation: 309899
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 :-)
Upvotes: 3