Skip to content

Quantity is mutable but defines a __hash__ method #761

Closed

Description

@lpsinger

The astropy.units.Quantity class is mutable because its value and unit properties both have setters, but it also declares a __hash__ method. Usually, only immutable objects should be hashable.

Here are two distinct Quantities:

>>> from astropy import units as u
>>> a = 5 * u.second
>>> b = 6 * u.second

And here they are as keys of a dictionary:

>>> c = {a: 'foo', b: 'bar'}
>>> c
{<Quantity 5 s>: 'foo', <Quantity 6 s>: 'bar'}

Since the two Quantities are mutable, we can change the properties of one of them to make them equal and render one of the dictionary values inaccessible:

>>> a.value = 6
>>> c
{<Quantity 6 s>: 'foo', <Quantity 6 s>: 'bar'}
>>> c[a]
'bar'
>>> c[b]
'bar'

Activity

  1. mdboom commented on Feb 11, 2013

    @mdboom
    Contributor

    Did we mean for it to be mutable? I recall some discussion (that I can't currently find) that it would be best if they were immutable.

  2. lpsinger commented on Feb 11, 2013

    @lpsinger
    ContributorAuthor

    @mdboom, there is some discussion of the __hash__ implementation in #445.

  3. astrofrog commented on Feb 11, 2013

    @astrofrog
    Member

    It looks like we all agreed in #445 that Quantity should be immutable, so it must have been an oversight. It should be fixed to be made immutable.

  4. added a commit that references this issue on Feb 11, 2013
    40a93c1
  5. eteq commented on Feb 11, 2013

    @eteq
    Member

    See #762 - that removes the value setter (looks like there already was no setter for unit).

  6. astrofrog commented on Feb 12, 2013

    @astrofrog
    Member

    Can be closed once #762 is merged.

  7. eteq commented on Feb 12, 2013

    @eteq
    Member

    Actually, it should get closed automatically after merge, because I put "Closes #761" in one of the commit messages. We'll see if it works...

  8. eteq commented on Feb 12, 2013

    @eteq
    Member

    And so it did. Yay github!

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

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions