Python与C++中的保护评估
guard evaluation in Python vs C++
就在最近,我浏览了我的一段代码(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
现在我有两个问题:
- 我相信类似的情况本可以被最好地抓住C++,因为它编译代码并将首先产生警告。允许我知道我错了吗
- 另一个问题是我们使用
py_compile.compile('file_name')
只是验证语法。难道Python中没有任何模块可以捕获这种失误
由于python是一种松散类型的语言,因此分析变量类型的代码变得困难(我认为这是不可能的)。我们可以使用pep8
或pylint
来分析代码。他们只能根据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
使用保护表达式。
相关文章:
- std::condition_variable::wait()如何评估给定的谓词
- 有充分的理由在h文件中使用include保护而不是cpp文件吗
- 为什么在保护模式下继承升级不起作用
- 访问被拒绝后,c++中的故障保护代码
- C++:无法访问声明的受保护成员
- 为什么您需要C++头文件的包含保护
- lock_guard是否保护返回值
- c++11评估顺序(未定义的行为)
- 如何在GTK程序运行时禁用屏幕保护程序/电源管理/屏幕消隐
- 继承和友元函数,从基类访问受保护的成员
- 为什么派生类的好友不能使用受保护的成员?
- C++:为什么无法在派生类中访问受保护的构造函数?
- 如何使用"equal to"以外的评估编写开关语句
- 嵌套 if 中没有返回评估
- 懒惰的参数评估try_emplace?
- 公共/私有/受保护是否会更改内存中结构的排列?
- 在实践中,在运行时为零的乘法中是否有任何"lazy"评估
- 如何改进一堆在已知值范围内评估变量的 else-if 条件?
- C++17:使用 std::optional 来评估枚举是否包含值
- Python与C++中的保护评估