8000 ENH: allow addition of custom attributes to arrays · Issue #28397 · numpy/numpy · GitHub
[go: up one dir, main page]

Skip to content
ENH: allow addition of custom attributes to arrays #28397
Open
@mdhaber

Description

@mdhaber

Proposed new feature or change:

Custom classes allow new attributes to be attached to instances of the class.

class MyClass: 
    pass
x = MyClass()
x.attribute = 1
x.attribute  # 1

NumPy arrays don't currently allow this.

import numpy as np
y = np.asarray(1)
y.attribute = 1
# AttributeError: 'numpy.ndarray' object has no attribute 'attribute' and no __dict__ for setting new attributes

Is this intentional, and would this be considered as an enhancement?

Use case: library functions that return a single NumPy array may wish to return additional information. For instance, functions in scipy.special currrently return the result of the requested calculation, but it would be useful for them to provide error estimates where possible. There is typically not a way to add this information in a backward-compatible way without introducing a new argument (e.g. return_error) that changes the output type, a pattern that has fallen out of style1. Also, if new functions were to begin to return tuples or rich objects with separate value and error attributes, they would no longer be as convenient to work with in expressions. A proposed solution might be to continue to return regular arrays, but add an attribute to them that users can access if they are interested in the error estimate.

Update: an officially sanctioned error_estimate (or other similarly named) attribute, if we're concerned about name collisions and typing, would suffice.

Footnotes

  1. For good reason!

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

      0