Skip to content

Group.__contains__ with nexus classes always returns True #241

Open
@jl-wynen

Description

@jl-wynen

Given a Group group, the following always evaluates to True:

NXdata in group

And the same applies to all NX classes.

The reason is that we don't define Group.__contains__. So Python uses the fallback for mappings:

    def __contains__(self, key):
        try:
            self[key]
        except KeyError:
            return False
        else:
            return True

But group[NXdata] returns an empty dict if there is no NXdata in the group. So __contains__ is always True.

This is surprising behaviour. I think we have two options to fix it without breaking anything:

  1. Actually check whether there are any children with the given class. This fixes the use case I have. But it creates an inconsistency between __contains__ and __getitem__.
  2. Raise a TypeError when __contains__ is called with anything but a `str. This also creates an inconsistency. But I think this one is less severe.

Alternatively, we could change the behaviour of __getitem__ to raise when there is no child with the given class.

Or we leave it as. This keeps the mapping API consistent. But this can easily lead to errors downstream.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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