惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 叶小钗
D
Docker
GbyAI
GbyAI
Y
Y Combinator Blog
Google DeepMind News
Google DeepMind News
G
Google Developers Blog
P
Proofpoint News Feed
云风的 BLOG
云风的 BLOG
雷峰网
雷峰网
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Stack Overflow Blog
Stack Overflow Blog
WordPress大学
WordPress大学
小众软件
小众软件
Engineering at Meta
Engineering at Meta
酷 壳 – CoolShell
酷 壳 – CoolShell
I
InfoQ
B
Blog
H
Help Net Security
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 聂微东
The GitHub Blog
The GitHub Blog
A
About on SuperTechFans
B
Blog RSS Feed
Microsoft Security Blog
Microsoft Security Blog

jdhao's digital space

Conversion between base64 and OpenCV or PIL Image 腾讯云对象存储博客图床开启 CDN 加速(不需要购买额外域名) Search and Replace in Multiple Files in Vim/Neovim Change Table Column Width in LaTeX Image or Table Side by Side in LaTeX LaTeX 并排显示图像或表格 Firenvim: Neovim inside Your Browser Content inside HTML tags missing in Latest Hugo? Creating Markdown Front Matter with Ultisnips Labelme JSON 标注格式转 voc XML 格式 Nifty Nvim Techniques That Make My Life Easier -- Series 6 macOS 下如何为视频制作字幕 Running Command Asynchronously inside Neovim Resolving Merge Conflict after Git Stash Pop Pylint: command not found? A Hands-on Experience with Neovim's Built-in LSP Support How to Convert PDF to Images with Imagemagick 互联网上常用缩略语集锦 File Backup in Neovim Converting PDF Pages to Images with Poppler Nifty Nvim Techniques That Make My Life Easier -- Series 5 Neovim Configuration for System-wide Use How to sort a list of tuple or list in Python -- lambda or itemgetter? Building A Vim Statusline from Scratch 人类第一颗原子弹爆炸始末 Distributed Training in PyTorch with Horovod Learning Expect Programming Essential Knowledge about SSH Nifty LaTeX Techniques -- Series 1 更改 Adsense 邮寄地址,重新寄送 PIN
Why is Wrong Stacktrace Printed for My Code?
2021-03-13 · via jdhao's digital space

The other day, when I was updating the source code with the project running, I noticed that the exception stack trace printed is not right, i.e., the printed error line is actually not the line that is triggering the exception.

Why did this happen? Is it related to the modification to the source file? At first, I thought it absurd. Based on my knowledge, when Python runs the source code, it will load it into memory. Since it is executing the code in the memory, so it should print the offending line that is kept in the memory.

To figure it out, I write the following code (test.py):

import time

time.sleep(10)
print(1/0)

I run it (python test.py), then add something below the time statement:

import time

time.sleep(10)
# some comment
print(1/0)

Then program reaches the print statement and printed the following exception:

Traceback (most recent call last):
  File "test.py", line 4, in <module>
    # some comment
ZeroDivisionError: division by zero

Surprisingly, the stack trace printed is the 4th line in the modified test.py, not the original 4th line (print(1/0)).

So my perception of how Python runs its code is not fully correct. I searched on the internet and found some explanation about this, for example, discussion here.

When Python run a source code, it will first compile the source code into the so called bytecode. Then the bytecode is executed by the Python virtual machine.

So what is really running is the bytecode, not the original source code. We can use the dis package in standard library to inspect the bytecode produced by Python.

import dis

my_str = "import time\n\ntime.sleep(10)\nprint(1/0)"
print(dis.dis(my_str))

It will show the bytecode along with other infos for the source code:

│  1           0 LOAD_CONST               0 (0)
│              2 LOAD_CONST               1 (None)
│              4 IMPORT_NAME              0 (time)
│              6 STORE_NAME               0 (time)
│  3           8 LOAD_NAME                0 (time)
│             10 LOAD_METHOD              1 (sleep)
│             12 LOAD_CONST               2 (10)
│             14 CALL_METHOD              1
│             16 POP_TOP
│  4          18 LOAD_NAME                2 (print)
│             20 LOAD_CONST               3 (1)
│             22 LOAD_CONST               0 (0)
│             24 BINARY_TRUE_DIVIDE
│             26 CALL_FUNCTION            1
│             28 POP_TOP
│             30 LOAD_CONST               1 (None)
│             32 RETURN_VALUE

Number in the first column corresponds to the code line in the original script. For example, the first line (import time) is turned into 4 bytecode instructions.

As a result, the original source code is not kept by Python in the memory. When an exception happens, python will try to find the corresponding source file and print the exact line in this source file. It does not check whether the source file has been changed since running. Hence, the mismatch between the printed exception line and the actual exception line.

So this is just how Python works under the hood. There are discussion on changing this behaviour, but it seems that the Python core developers are not going to change it any time soon.

References#