Skip to content

AtomGroups are not hashable on python 3 #1397

@jbarnoud

Description

@jbarnoud

Expected behaviour

An AtomGroup is hashable, it can therefore be placed in a set or as a dictionary key. topologyattr.Bonds.fragments, that creates a set of AtomGroups, works as intended.

Actual behaviour

Attempting to get the hash of an AtomGroup on python 3 raises the following error:

TypeError: unhashable type: 'AtomGroup'

It works on python 2.

In python 3, a class that defines __eq__ but not __hash__ has __hash__ set to None, see https://docs.python.org/3/reference/datamodel.html#object.__hash__. So we should define a __hash__ method for the GroupBase class. I think this method could look like:

def __hash__(self):
    return hash((self.universe, self.__class__, self._ix))

Code to reproduce the behaviour

#!/usr/bin/env python

import MDAnalysis as mda
from MDAnalysisTests.datafiles import TPR, XTC

u = mda.Universe(TPR, XTC)

print(hash(u.atoms))

Currently version of MDAnalysis:

(run python -c "import MDAnalysis as mda; print(mda.__version__)")
'0.16.2-dev0' (7652710)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions