V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
codists
V2EX  ›  Python

求助,执行字节码指令时栈的具体变化是怎么样的?

  •  
  •   codists ·
    codists · 2022-05-21 10:27:31 +08:00 · 2123 次点击
    这是一个创建于 677 天前的主题,其中的信息可能已经有所发展或是发生改变。

    一、问题描述

    1.1 源码

    import dis
    print(dis.dis('s[a] += b'))
    

    输出:

      1           0 LOAD_NAME                0 (s)
                  2 LOAD_NAME                1 (a)
                  4 DUP_TOP_TWO
                  6 BINARY_SUBSCR
                  8 LOAD_NAME                2 (b)
                 10 INPLACE_ADD
                 12 ROT_THREE
                 14 STORE_SUBSCR
                 16 LOAD_CONST               0 (None)
                 18 RETURN_VALUE
    None
    

    1.2 问题

    以上代码来自于《 Fluent Python 2 》 p55-p56 ,我自己按照字节码指令的顺序绘制栈的变化,得不到代码执行的结果,请各位大佬帮忙看下问题出在哪里。

    二、问题分析

    https://github.com/codists/learnings/blob/main/python/images/temp.jpg 以上是我按照字节码命令绘制的栈变化,但是最后得到的结果是s[a]+b=s[a]+b

    请问各位大佬,是我的绘制过程有问题(如:某一个操作其实没有入栈,或者某一个操作应该有出栈)还是说我理解有问题(如:其实字节码指令描述的并不是连续的过程)?麻烦各位大佬解答的时候最好能提供一下参考资料,谢谢啦。

    4 条回复    2022-05-21 15:29:28 +08:00
    sikariba
        1
    sikariba  
       2022-05-21 11:25:16 +08:00
    我自己画出来的也不对,不过能确定你地址 6 、10 的地方画错了,6 的那里要出栈两个再写入( Binary operations remove the top of the stack (TOS) and the second top-most stack item (TOS1) from the stack. They perform the operation, and put the result back on the stack.),10 是 inplace 的操作,你 append 了。咱俩可以讨论一下
    sikariba
        2
    sikariba  
       2022-05-21 11:44:38 +08:00
    10 的那里再出一次栈就可以画出来了
    chenxytw
        3
    chenxytw  
       2022-05-21 11:46:10 +08:00
    6, 10 画错了。
    两个都是要先出栈两次。只是 10 的 TOS1 如果支持 inplace ,等同于出栈一次。
    codists
        4
    codists  
    OP
       2022-05-21 15:29:28 +08:00
    @sikariba
    @chenxytw
    感谢两位大佬的解答,6 、10 这两步出栈确实是关键点,是我以前没理解到位。Thx for your enlighten answers again 。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3326 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 13:30 · PVG 21:30 · LAX 06:30 · JFK 09:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.