[Numpy-discussion] proper use of __new__

Darren Dale dsdale24@gmail....
Tue Jul 21 13:23:16 CDT 2009

On Tue, Jul 21, 2009 at 1:26 PM, Pierre GM<pgmdevlist@gmail.com> wrote:
> On Jul 21, 2009, at 10:58 AM, Darren Dale wrote:
>> 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:
> (Note to self: I should add the information in Subclasses to the
> documentation and make it consistent. </sigh>).
> The words of caution were intended to remind that setting the value
> of  new array attributes in __new__ only could lead to problems, as
> it's possible to transform a ndarray into a subclass with a view (that
> is, calling __array_finalize__ without calling __new__). In the Simple
> Example of the doc, if .info cannot be None but must have a default
> DEFAULT, you should have a
>  >>> self.info = getattr(obj, 'info', DEFAULT)
> in your __array_finalize__

I think this has been addressed in quantities, but thanks for the reminder.

> Without access to your code, I'm likely to speak beyond myself here
> (could you send me a link to the latest version ?), but if you need to
> rescale the units, make sure it's done in __array_finalize__ as well,
> with something like
> units = getattr(obj, 'units', None)
> if units is not None:
>     self.rescale(units)
> else:
>      self.units = units

Thanks for the suggestion, but I don't think there would be a reason
to rescale when taking a view. view only takes dtype and type
arguments, there is no way to specify what units you want to convert
to. You either get the same units as self, or you get some kind of a
view that doesnt support units. With the constructor, it is possible
to pass an existing quantity (with units) and also specify the desired
units, in which case we attempt to convert the old quantity into the
new units.

> Once again, browsing your code would let me give you some more
> adequate answers...

For some reason, I am not able to browse the repository at launchpad,
but you can get the code with "bzr branch lp:python-quantities" or
from http://pypi.python.org/pypi/quantities . The branch that works
with the __array_prepare__ patch I sent can be retrieved with "bzr
branch lp:dsdale24/python-quantities/quantities-array-prepare". The
implementations of __new__ are in quantities/quantity.py and
quantities/unitquantity.py and quantities/uncertainquantity. It is not
intended to support transforming a Quantity into a UnitQuantity by
using a view, there should never be a reason to do this. So I guess I
am only concerned about quantity and uncertainquantity.


More information about the NumPy-Discussion mailing list