python风格规范之do not compare types, for exact checks use `is` / `is not`, for instance chec
python风格规范之do not compare types
规范错误/警告描述
PEP 8: E721 do not compare types, for exact checks use `is` / `is not`, for instance checks use `isinstance()`
规范错误描述(示例)
def check_type(input_message):
if type(input_message) == str:
print("{} is a string.".format(input_message))
else:
print("{} is not a string.".format(input_message))
规范错误认知
关于type不要做比较,更希望使用is/is not做精确的判断。也可使用方法isinstance()进行替代。

正确示例
# 正确示例1
def check_type(input_message):
if type(input_message) is str:
print("{} is a string.".format(input_message))
else:
print("{} is not a string.".format(input_message))
# 正确示例2
def check_type(input_message):
if isinstance(input_message,str):
print("{} is a string.".format(input_message))
else:
print("{} is not a string.".format(input_message))
Reference
\text{Reference}
Reference:
python - 风格规范