代码在这:
https://gist.github.com/guyskk/8ae152653220800e9b9a
被注释掉的都会报 KeyError
最后那句print(dict([(k, items[k]) for k in keys]))
在 python3 会报错,python2 正常
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() 所指代的内容不同,我猜测是生成器的实现有所不同了 |
2
fy 2016-01-23 00:02:22 +08:00
>>> print([id(locals()) for k in module_keys])
[53111664, 53111664] >>> id(locals()) 41054976 确实如此 |
3
guyskk OP 被注释掉的语句都是会报错的,我在 python2.7 和 python3.4 上都试了
|
4
guyskk OP class A:
a = 42 b = list(a + i for i in range(10)) b = [a + i for i in range(10)] 第 1 个 b 那里会报错,第 2 个正常 好像是作用域的问题 |
5
realityone 2016-01-23 00:22:55 +08:00 1
|
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 |
7
guyskk OP 搞定了,多谢各位帮忙
|