Can namedtuples be used in set()?

Viewed 564

I know that namedtuple is a factory function to create classes with immutable data fields. I'm assuming they are hashable so that they can be used in sets. My worry is if there are any gotchas associated with using namedtuples in sets. e.g. are there issues if there are nested namedtuples?

1 Answers

Yes, they are hashable, and can be used in sets, like tuples.
The gotcha is that a tuple of mutable objects can change underneath you.

Tuples composed of immutable objects are safe in this regards.

Not sure it is a gotcha, but it is worth noting @user2357112supportsMonica's remark in the comments:

The other gotcha is that a namedtuple is still a tuple, and its __hash__ and __eq__ are ordinary tuple hash and equality. A namedtuple will compare equal to ordinary tuples or instances of unrelated namedtuple classes if the contents match.

Related