I would like to use NetworkX Graph
objects as keys in a Python dict
. However, I do not want the default behavior for comparison (i.e., by the address of the object). Instead, I would like isomorphic graphs to refer to be keys to the same elements in the dict
.
Is this behavior already implemented somewhere? I could not find any information in this direction.
If I have to implement it myself, is the following assessment realistic?
- Wrap
networkx.Graph
in a class. - Define
__eq__
such that it callsis_isomorphic
. - Define
__hash__
somehow (suggestions welcomed).
I think that I would have to make this wrapped Graph immutable, because:
If a class defines mutable objects and implements an
__eq__()
method, it should not implement__hash__()
, since the implementation of hashable collections requires that a key’s hash value is immutable (if the object’s hash value changes, it will be in the wrong hash bucket).
Here is an example of subclassing a networkx Graph and adding a eq and hash function as you describe. I'm not sure if it solves your problem but should be a start.
Outputs something like: