Skip to content

Current Results class has a conflict in key validation between setattr and setitem #3282

@lilyminium

Description

@lilyminium

Expected behavior

I can modify the same value in a Results class both by using __setitem__ and __setattr__. e.g.

def test_setattr_modify_item(self, results):
        setattr(results, "myattr", 0)
        assert results.myattr == 0
        results["myattr"] = 3
        assert results.myattr == 3

Actual behavior

The above test fails. This only happens when actions follow a specific order:

  • modify a value with setattr
  • then modify that value with setitem
  • then try to get back the modified value with getattr/ibute

This is because in the current Results code, __setattr__ actually sets the attribute. When this happens, attribute access happens with __getattribute__ rather than __getattr__. This means that while __setitem__ is modifying the key/value pair in Results.data, there is also an attribute that does not get modified. This attribute is what gets returned on attribute access.

While it may be easy to just tell users not to mix-and-match the setattr/setitem behaviour, it's apparently natural enough that it's causing the helix_analysis tests to fail (#3279).

Code to reproduce the behavior

import MDAnalysis as mda
from MDAnalysis.tests.datafiles import PSF, DCD,  GRO, PDB, TPR, XTC, TRR,  PRMncdf, NCDF

u = mda.Universe(PSF, DCD)

....

Current version of MDAnalysis

  • Which version are you using? (run python -c "import MDAnalysis as mda; print(mda.__version__)")
  • Which version of Python (python -V)?
  • Which operating system?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions