Do we need methods `__hash__()` and `__eq__()` for `Tensorli` ?
Closed this issue · 2 comments
In build_topo()
, we would ask if t
exists in set visited
, but how we determine whether two Tensorli
objects are equal ?
so do we need methods __hash__()
and __eq__()
for Tensorli
?
Hei :-)
Thank you for the questions. I assume you are asking this to ensure we do not add a node (i.e. Tensorli
) twice.
topo: list["Tensorli"] = []
visited = set()
# build topological order such that we calculate and pass the gradients
# back in the correct order
def build_topo(t):
if t not in visited:
visited.add(t)
for child in t._prev:
build_topo(child)
topo.append(t)
I assume you looked into the Python documentation and saw that (https://docs.python.org/3/library/stdtypes.html#set):
The elements of a set must be hashable.
In the documentation for hashable
(https://docs.python.org/3/glossary.html#term-hashable):
Most of Python’s immutable built-in objects are hashable; mutable containers (such as lists or dictionaries) are not; immutable containers (such as tuples and frozensets) are only hashable if their elements are hashable. Objects which are instances of user-defined classes are hashable by default. They all compare unequal (except with themselves), and their hash value is derived from their id().
So Tensorli
objects are all unequal except with themselves --> exactly the behaviour we want for the set
.
Does that answer your question :-)?
Hei :-)
Thank you for the questions. I assume you are asking this to ensure we do not add a node (i.e.
Tensorli
) twice.topo: list["Tensorli"] = [] visited = set() # build topological order such that we calculate and pass the gradients # back in the correct order def build_topo(t): if t not in visited: visited.add(t) for child in t._prev: build_topo(child) topo.append(t)I assume you looked into the Python documentation and saw that (https://docs.python.org/3/library/stdtypes.html#set): The elements of a set must be hashable.
In the documentation for
hashable
(https://docs.python.org/3/glossary.html#term-hashable):Most of Python’s immutable built-in objects are hashable; mutable containers (such as lists or dictionaries) are not; immutable containers (such as tuples and frozensets) are only hashable if their elements are hashable. Objects which are instances of user-defined classes are hashable by default. They all compare unequal (except with themselves), and their hash value is derived from their id().
So
Tensorli
objects are all unequal except with themselves --> exactly the behaviour we want for theset
.Does that answer your question :-)?
Oh, you re right, we just wanna avoid same node, rather than same node.data
Thank you and sorry for this dumb question 😄