I have a function in python that does error checking on a string. If the function finds an error it will return a tuple with an error code and an identifier for that error. Later in the program I have the function that handles the error. It accepts the tuple into two variables.
errCode, i = check_string(s,pathType)
check_string is the function that produces the tuple. What I want it to does is return just zero if there is no error. When a zero is returned the above code seems to fail because there is nothing for the variable i.
Is there an easy way to get this to work or do I just need to have the program return a tuple of 0 and 0 if no error is found?
I would use the exception system for this.
class StringError(Exception):
NO_E = 0
HAS_Z = 1
def string_checker(string):
if 'e' not in string:
raise StringError('e not found in string', StringError.NO_E)
if 'z' in string:
raise StringError('z not allowed in string', StringError.HAS_Z)
return string.upper()
s = 'testing'
try:
ret = string_checker(s)
print 'String was okay:', ret
except StringError as e:
print 'String not okay with an error code of', e.args[1]
You could use None as the value for error
def check_string(s,pathType):
# No error
return (None, i)
Why not simply check the length of the tuple before trying to retrieve the values?
err_tup = check_String(s, pathType)
if len(err_tup) == 2:
errCode, i = err_tup
else: # assuming it can only be 1 otherwise
errCode = err_tup
This would work without making any changes to the rest of your code that generates the tuple, and is semantically clear.
Based on "Simple is better than complex."
If you are going to return zero:
foo = func()
if not foo:
print 'No errors'
else:
# foo is tuple
来源:https://stackoverflow.com/questions/11708568/tuple-with-missing-value