相关疑难解决方法(0)

为什么CPython中的id({})== id({})和id([])== id([])?

为什么CPython(没有关于其他Python实现的线索)有以下行为?

tuple1 = ()
tuple2 = ()                                                                                                   
dict1 = {}
dict2 = {}
list1 = []
list2 = []
# makes sense, tuples are immutable
assert(id(tuple1) == id(tuple2))
# also makes sense dicts are mutable
assert(id(dict1) != id(dict2))
# lists are mutable too
assert(id(list1) != id(list2))
assert(id(()) == id(()))
# why no assertion error on this?
assert(id({}) == id({}))
# or this?
assert(id([]) == id([]))
Run Code Online (Sandbox Code Playgroud)

我有一些想法可能,但找不到具体原因.

编辑

进一步证明格伦和托马斯的观点:

[1] id([])
4330909912
[2] x = []
[3] …
Run Code Online (Sandbox Code Playgroud)

python identity cpython python-internals

26
推荐指数
2
解决办法
1787
查看次数

有人可以解释python生成器表达式中空dicts的行为吗?

当我们偶然发现下面的行为时,我和一些朋友正在讨论与Python内存管理相关的事情:

In [46]: l = ({} for _ in range(6))

In [47]: [ id(i) for i in l]
Out[47]:
[4371243648, # A
 4371245048, # B
 4371243648, # A
 4371245048, # B
 4371243648, # etc.
 4371245048]
Run Code Online (Sandbox Code Playgroud)

令人惊讶的是,我们似乎没有明确定义的行为:每次dict既不是新的也不是每次都是相同的引用.

最重要的是,我们得到了这种奇怪的行为(代码不是在这两个片段之间的解释器中运行).

In [48]: m = ({} for _ in range(6))

In [49]: [ id(i) for i in m]
Out[49]:
[4371154376, # C
 4371245048, # B (same B as above!)
 4371154376, # C
 4371245048, # B
 4371154376,
 4371245048]
Run Code Online (Sandbox Code Playgroud)

谁能解释这种行为?使用list comprehensions(l = [{} for _ …

python dictionary generator-expression

5
推荐指数
1
解决办法
53
查看次数