Python中的动态语义错误 [英] Dynamic Semantic errors in Python
问题描述
我遇到了这个面试问题。这个问题似乎很有趣。所以,我把它在这里。
i came across this as an interview question. This question seemed interesting. So, i am posting it here.
考虑给出像零除的语义错误的操作。默认情况下,python编译器给出输出无效操作或某事。我们可以控制由Python编译器给出的输出,例如打印一些其他错误消息,跳过零操作除法,并继续其余的指令?
此外,如何评估运行时语义检查的成本?
这里有很多python专家。我希望有人会对这一点点亮。提前感谢。
Consider the operation which gives semantic error like division by zero. By default, python compiler gives output like "Invalid Operation" or something. Can we control the output that is given out by Python compiler, like print some other error message, skip that division by zero operation, and carry on with rest of the instructions?
And also, how can i evaluate the cost of run-time semantic checks?
There are many python experts here. I am hoping someone will throw some light on this. Thanks in advance.
推荐答案
我们可以控制Python编译器提供的输出,例如打印一些其他错误信息,跳过这个除法由零操作,并继续其余的指令?
Can we control the output that is given out by Python compiler, like print some other error message, skip that division by zero operation, and carry on with rest of the instructions?
不,你不能。你可以使用尝试...除了
块手动包装每个危险的命令,但我假设你正在谈论自动恢复到 / em> a 尝试...除非
阻止,甚至完全自动。
No, you cannot. You can manually wrap every dangerous command with a try...except
block, but I'm assuming you're talking about an automatic recovery to specific lines within a try...except
block, or even completely automatically.
通过调用 sys.excepthook
,或者任何外部范围,如果你赶上它早,内部范围消失了。您可以使用 sys.settrace
在CPython中,但只有一个实现细节,但由于外部范围消失了没有可靠的recorvery机制。
By the time the error has fallen through such that sys.excepthook
is called, or whatever outer scope if you catch it early, the inner scopes are gone. You can change line numbers with sys.settrace
in CPython although that is only an implementation detail, but since the outer scopes are gone there is no reliable recorvery mechanism.
如果你尝试使用幽默的 goto
愚人模块(使用我刚刚描述的方法)跳跃块甚至在文件:
If you try to use the humorous goto
April fools module (that uses the method I just described) to jump blocks even within a file:
from goto import goto, label
try:
1 / 0
label .foo
print("recovered")
except:
goto .foo
您会收到以下错误:
Traceback (most recent call last):
File "rcv.py", line 9, in <module>
goto .foo
File "rcv.py", line 9, in <module>
goto .foo
File "/home/joshua/src/goto-1.0/goto.py", line 272, in _trace
frame.f_lineno = targetLine
ValueError: can't jump into the middle of a block
所以我很确定这是不可能的。
so I'm pretty certain it's impossible.
还有,如何评估运行时语义检查的成本?
And also, how can i evaluate the cost of run-time semantic checks?
我不知道是什么,但你可能在寻找 line_profiler
:
I don't know what that is, but you're probably looking for a line_profiler
:
import random
from line_profiler import LineProfiler
profiler = LineProfiler()
def profile(function):
profiler.add_function(function)
return function
@profile
def foo(a, b, c):
if not isinstance(a, int):
raise TypeError("Is this what you mean by a 'run-time semantic check'?")
d = b * c
d /= a
return d**a
profiler.enable()
for _ in range(10000):
try:
foo(random.choice([2, 4, 2, 5, 2, 3, "dsd"]), 4, 2)
except TypeError:
pass
profiler.print_stats()
输出:
Timer unit: 1e-06 s
File: rcv.py
Function: foo at line 11
Total time: 0.095197 s
Line # Hits Time Per Hit % Time Line Contents
==============================================================
11 @profile
12 def foo(a, b, c):
13 10000 29767 3.0 31.3 if not isinstance(a, int):
14 1361 4891 3.6 5.1 raise TypeError("Is this what you mean by a 'run-time semantic check'?")
15
16 8639 20192 2.3 21.2 d = b * c
17 8639 20351 2.4 21.4 d /= a
18
19 8639 19996 2.3 21.0 return d**a
因此,运行时语义检查在这种情况下将占用36.4%的运行时间 foo
。
So the "run-time semantic check", in this case would be taking 36.4% of the time of running foo
.
如果要手动计算特定块的大小, code> timeit ,但小于你想要的分析器,而不是使用两个 time.time()
调用是相当不准确的方法)我建议 Steven D'Aprano的秒表上下文管理器。
If you want to time specific blocks manually that are larger than you'd use timeit
on but smaller than you'd want for a profiler, instead of using two time.time()
calls (which is quite an inaccurate method) I suggest Steven D'Aprano's Stopwatch context manager.
这篇关于Python中的动态语义错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!