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
guyskk
V2EX  ›  Python

遇到一个奇怪的问题,怀疑是 python 的 bug

  •  
  •   guyskk ·
    guyskk · 2016-01-22 23:51:17 +08:00 · 2453 次点击
    这是一个创建于 3016 天前的主题,其中的信息可能已经有所发展或是发生改变。

    代码在这:
    https://gist.github.com/guyskk/8ae152653220800e9b9a
    被注释掉的都会报 KeyError
    最后那句print(dict([(k, items[k]) for k in keys]))在 python3 会报错,python2 正常

    7 条回复    2016-01-23 00:39:06 +08:00
    fy
        1
    fy  
       2016-01-23 00:01:00 +08:00
    楼主的代码报错:

    k1 = 'v1'
    k2 = 'v2'

    module_items = locals()
    module_keys = ['k1', 'k2']
    print({k: locals()[k] for k in module_keys}) # 这一句


    我的测试结果( Python 3.4 ):

    >>> print({k: [locals(), k] for k in module_keys})
    {'k1': [{'.0': <list_iterator object at 0x03299E10>, 'k': 'k2'}, 'k1'], 'k2': [{'.0': <list_iterator object at 0x03299E10>, 'k': 'k2'}, 'k2']}
    >>>
    >>>
    >>> locals()
    {'k2': 'v2', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, 'module_keys': ['k1', 'k2'], 'module_items': {...}, 'k1': 'v1', '__builtins__': <module 'builtins' (built-in)>, '__package__': None, '__name__': '__main__', '__doc__': None}

    确实是报错了,我试着输出了 locals()

    可以看到 locals() 所指代的内容不同,我猜测是生成器的实现有所不同了
    fy
        2
    fy  
       2016-01-23 00:02:22 +08:00
    >>> print([id(locals()) for k in module_keys])
    [53111664, 53111664]
    >>> id(locals())
    41054976

    确实如此
    guyskk
        3
    guyskk  
    OP
       2016-01-23 00:04:02 +08:00
    被注释掉的语句都是会报错的,我在 python2.7 和 python3.4 上都试了
    guyskk
        4
    guyskk  
    OP
       2016-01-23 00:09:29 +08:00
    class A:
    a = 42
    b = list(a + i for i in range(10))
    b = [a + i for i in range(10)]

    第 1 个 b 那里会报错,第 2 个正常

    好像是作用域的问题
    fy
        6
    fy  
       2016-01-23 00:25:36 +08:00   ❤️ 1
    补充一个 Python 2.7 的:

    Python 2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> module_keys = ['k1', 'k2']
    >>>
    >>> print([id(locals()) for k in module_keys])
    [40479312, 40479312]
    >>> id(locals())
    40479312
    guyskk
        7
    guyskk  
    OP
       2016-01-23 00:39:06 +08:00
    搞定了,多谢各位帮忙
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2863 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 14:57 · PVG 22:57 · LAX 07:57 · JFK 10:57
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.