[Numpy-discussion] proper use of __new__

Darren Dale dsdale24@gmail....
Tue Jul 21 09:58:56 CDT 2009


http://docs.scipy.org/doc/numpy/user/basics.subclassing.html#simple-example-adding-an-extra-attribute-to-ndarray
includes an example where an instance attribute is set in __new__ .
However, there is a warning at http://www.scipy.org/Subclasses:

-----
Some words of caution

The definition in the __new__ method of default values for the
subclass attributes is strongly discouraged for several reasons:

    * It is not thread-safe.
    *

      An array of a given subclass can be created from an array of
another subclass without any call to the __new__ method at all. This
situation occurs with the use of the view method. In that case, we
must still initialize the attributes of the new subclass with the
__array_finalize__ method.
-----

In my quantities subclasses, I have implementations for __new__ like:

    def __new__(cls, data, units='', dtype=None, copy=True):
        if isinstance(data, cls):
            if units:
                data = data.rescale(units)
            return np.array(data, dtype=dtype, copy=copy, subok=True)

        ret = np.array(data, dtype=dtype, copy=copy).view(cls)
        ret._dimensionality.update(validate_dimensionality(units))
        return ret

and another definition for __new__ that is used to implement global
UnitQuantity instances representing immutable things like meter and
foot, and that __new__ implementation sets several instance
attributes. I thought this was acceptable practice, based on the
discussion in basics.subclassing.html, but now I'm not sure. How would
I safely set instance attributes based on args/kwargs passed to the
constructor, if not in __new__?

Thanks,
Darren


More information about the NumPy-Discussion mailing list