从 Python 架子检索前后对象更改的哈希值
Hash of object changes before and after retrieving from Python shelf
问题
我生成一个 chimera
图,它基本上是一个 dwave_networkx
对象。 dwave_networkx
继承自 networkx
图 class。我把它存放在 Python 架子上。原图的hash和从架子上找回来的hash不一样,想不通是什么原因。我要求两者相同。
代码
import dwave_networkx as dnx
import shelve
def generate_graph(N):
graph = dnx.chimera_graph(1, N, 4)
graph_id = ""
for node in graph.nodes:
graph.nodes[node]['weight'] = _get_node_weight() # A function that returns a random number
for edge in graph.edges:
graph.edges[edge]['weight'] = _get_edge_weight() # A function that returns a random number
graph_id = str(hash(graph))
return graph, graph_id
shelf = shelve.open("graphs.shelf")
ids = []
for i in range(10):
graph, id = generate_graph(5)
ids.append(id)
shelf[id] = {"graph": graph}
for i in ids:
print(i, hash(shelf[i]["graph"])
# The two values in each row turn out to be different!
shelf.close()
这可能是什么原因?
可能是因为 shelf
对象基本上是在创建原始图形的副本。看这个例子:
shelf = shelve.open("dummy.shelf")
# List are mutable, just like the Graphs
x = [1, 2, 3]
# Add the the list to shelf
shelf["1"] = x
print(id(x), id(shelf["1"]))
# 5314942976 5314799232
shelf.close()
如您所见,创建了原始列表的副本并将其添加到货架(类似于图形发生的情况,因为它们是可变的 类)。您可以查看 implementation here 了解更多信息。
参考文献:
问题
我生成一个 chimera
图,它基本上是一个 dwave_networkx
对象。 dwave_networkx
继承自 networkx
图 class。我把它存放在 Python 架子上。原图的hash和从架子上找回来的hash不一样,想不通是什么原因。我要求两者相同。
代码
import dwave_networkx as dnx
import shelve
def generate_graph(N):
graph = dnx.chimera_graph(1, N, 4)
graph_id = ""
for node in graph.nodes:
graph.nodes[node]['weight'] = _get_node_weight() # A function that returns a random number
for edge in graph.edges:
graph.edges[edge]['weight'] = _get_edge_weight() # A function that returns a random number
graph_id = str(hash(graph))
return graph, graph_id
shelf = shelve.open("graphs.shelf")
ids = []
for i in range(10):
graph, id = generate_graph(5)
ids.append(id)
shelf[id] = {"graph": graph}
for i in ids:
print(i, hash(shelf[i]["graph"])
# The two values in each row turn out to be different!
shelf.close()
这可能是什么原因?
可能是因为 shelf
对象基本上是在创建原始图形的副本。看这个例子:
shelf = shelve.open("dummy.shelf")
# List are mutable, just like the Graphs
x = [1, 2, 3]
# Add the the list to shelf
shelf["1"] = x
print(id(x), id(shelf["1"]))
# 5314942976 5314799232
shelf.close()
如您所见,创建了原始列表的副本并将其添加到货架(类似于图形发生的情况,因为它们是可变的 类)。您可以查看 implementation here 了解更多信息。
参考文献: