Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to rewrite a specific frame in a traceback?
    text
    copied!<p>In python you can compile() string to be executed faster with exec(). But as soon as i use it, we lost information when an exception happen in the exec.</p> <p>For example, here is a code snippet that calling a unknown method (for demo purposes):</p> <pre><code>code = 'my_unknown_method()' bytecode = compile(code, '&lt;string&gt;', 'exec') </code></pre> <p>And later, i'm calling exec on that bytecode:</p> <pre><code>exec bytecode </code></pre> <p>The traceback showed is:</p> <pre><code>Traceback (most recent call last): File "test.py", line 3, in &lt;module&gt; exec bytecode File "&lt;string&gt;", line 1, in &lt;module&gt; NameError: name 'my_unknown_method' is not defined </code></pre> <p>The "exec()" frame is now obscure. I would like to have a better exception like:</p> <pre><code>Traceback (most recent call last): File "test.py", line 3, in &lt;module&gt; exec "my_unknown_method()" File "&lt;string&gt;", line 1, in &lt;module&gt; NameError: name 'my_unknown_method' is not defined </code></pre> <p>Any thoughts ?</p> <p>Notes:</p> <ul> <li>I don't want to use the second argument of compile (the filename)</li> <li>I have tested to play with inspect and modify f_code on the frame, but it's readonly attribute.</li> </ul> <p>EDIT: after looking more to sys.excepthook, i've seen that in python source code/traceback.c, when python want to show the line content, they are fopen() directly the file if found. No hook available at all to display our own content. The only way would be to create in real fake filename on disk ? Anyone ?</p> <p>EDIT2: i checked some jinja2 debug code, and they are rewriting traceback too, but not for content. Would i need a custom except hook ? My concerns with it is since it's not in the traceback itself, if an user/module/whatever take the exception, the traceback will not contain valuable information.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload