Tuple with missing value

末鹿安然 提交于 2019-12-06 16:31:53

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