Python与C++中的保护评估

guard evaluation in Python vs C++

本文关键字:保护 评估 C++ Python      更新时间:2023-10-16

就在最近,我浏览了我的一段代码(Python),其中严重遗漏了guard评估。我缩短了代码,使其成为一个简短的

>>> x = 4
>>> y = 0
>>> x >= 1 and (x/y) > 2
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    x >= 2 and (x/y) > 2
ZeroDivisionError: integer division or modulo by zero

这里我们需要添加保护

>>> x >= 1 and y != 0 and (x/y) > 2 # y!=0 is a guard
False

现在我有两个问题:

  1. 我相信类似的情况本可以被最好地抓住C++,因为它编译代码并将首先产生警告。允许我知道我错了吗
  2. 另一个问题是我们使用py_compile.compile('file_name')只是验证语法。难道Python中没有任何模块可以捕获这种失误

由于python是一种松散类型的语言,因此分析变量类型的代码变得困难(我认为这是不可能的)。我们可以使用pep8pylint来分析代码。他们只能根据PEP通知我们缩进和代码编写。

对于以下文件guard_eval.py

sherry@Sherry-Linux:~$ cat guard_eval.py 
x=6
y=0
if x >= 1 and (x/y) > 2:
        print True
else:
        print False
sherry@Sherry-Linux:~$ pep8 guard_eval.py 
guard_eval.py:1:2: E225 missing whitespace around operator
guard_eval.py:2:2: E225 missing whitespace around operator
guard_eval.py:4:1: W191 indentation contains tabs
guard_eval.py:6:1: W191 indentation contains tabs

pylint还提供代码评级:)

但在C++的情况下,我们可以将编译器修改为analyze code with the variable type,并在编译时提示用户对integer/integer division使用保护表达式。