Tuple with missing value

一个人想着一个人 提交于 2019-12-08 07:35:47

问题


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?


回答1:


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]



回答2:


You could use None as the value for error

def check_string(s,pathType):
    # No error
    return (None, i)



回答3:


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."




回答4:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!