Can we control the output generated by the Python compiler, for example, print another error message, skip this division by the zero operation, and follow the remaining instructions?
No, you canβt. You can manually wrap each dangerous command with a try...except block, but I assume that you are talking about automatic recovery for certain lines in a try...except block, or even completely automatically.
By the time the error has failed, so sys.excepthook is called or some other appearance, if you catch it earlier, the inner areas have disappeared. You can change the sys.settrace line sys.settrace in CPython, although this is only an implementation detail , but since the outer areas are gone there is no reliable mechanism of recurrence.
If you try to use the goto April fools humorous module (which uses the method just described) to jump blocks even inside the file:
from goto import goto, label try: 1 / 0 label .foo print("recovered") except: goto .foo
You will receive an error message:
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
therefore, I am sure that this is not possible.
And also, how can I estimate the cost of semantic runtime checks?
I don't know what it is, but you are probably looking for 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()
output:
Timer unit: 1e-06 s File: rcv.py Function: foo at line 11 Total time: 0.095197 s Line
Thus, the βsemantic check of runtime" in this case will occupy 36.4% of the time foo works.
If you want certain blocks manually to be larger than you would use timeit , but smaller than you would like for the profiler, instead of using two calls to time.time() (which is pretty inaccurate) I suggest Stephen D'Apano Stopwatch Context Manager .