#target isexpected to be one of x, y, or z, and nothing else.if target == x:run_x_code()elif target == y:run_y_code()else:run_z_code()
可以以断言代替注释,在违反时返回一个干净的错误:
assert target in (x, y, z)if target == x:run_x_code()elif target == y:run_y_code()else:assert target == zrun_z_code()
还有更好的方案:
if target == x:run_x_code()elif target == y:run_y_code()elif target == z:run_z_code()else:# This can never happen. But just incase it does...raiseRuntimeError("anunexpected error occurred")