astrofrog/astropy — pull request #28 by iguananaut (2013-05-02 22:41:29+00:00)
Title: Gets the tests at least passing with Quantity as an ndarray subclass

This required two changes in the existing behavior of the class (both of which could
be worked around, but for now these changes were the easiest way to get things
working):

1. Quantity.value always returns a Python type (such as `int` or `float`) for
scalar quantities, even if the underlying object is a Numpy scalar array.

2. Quantity instances have a default unit of unscaled_dimensionless (previously
it was erroneous to instantiate a Quantity without specifying a unit).

If either of those behaviors are undesirable I can find further workarounds.

There are also two other problems so far with the approach: `dir()` is made pretty unhelpful due to all the methods and attributes exposed from numpy arrays. Some of those may be worth exposing (especially for array Quantities--not so much for scalars). We might be able to patch that up a bit at least in IPython by further overriding `__dir__`.

The other is that a lot of the methods exposed have strange behavior on scalars. For example:

```
In [3]: q = Quantity(2, 'm')

In [4]: q.std()
←[0;31mERROR←[0m: TypeError: Object of type '' cannot be subtracted from a Quantity object. Subtraction is only supported between Quantity objects with compatible units. [astropy.units.quantity]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in ()
----> 1 q.std()

c:\Python27\lib\site-packages\numpy-1.7.0-py2.7-win32.egg\numpy\core\_methods.pyc in _std(a, axis, dtype, out, ddof, keepdims)
100 def _std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False):
101 ret = _var(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
--> 102 keepdims=keepdims)
103
104 if isinstance(ret, mu.ndarray):

c:\Python27\lib\site-packages\numpy-1.7.0-py2.7-win32.egg\numpy\core\_methods.pyc in _var(a, axis, dtype, out, ddof, keepdims)
75
76 # arr - arrmean
---> 77 x = arr - arrmean
78
79 # (arr - arrmean) ** 2

C:\MinGW\msys\1.0\home\embray\src\astropy\astropy\units\quantity.pyc in __sub__(self, other)
298 "Object of type '{0}' cannot be subtracted from a Quantity "
299 "object. Subtraction is only supported between Quantity "
--> 300 "objects with compatible units.".format(other.__class__))
301
302 def __mul__(self, other):

TypeError: Object of type '' cannot be subtracted from a Quantity object. Subtraction is only supported between Quantity objects with compatible units.
```

Obviously `std()` for a scalar shouldn't work, and on Numpy it causes an exception too, albeit a different one. In both cases the exception raised is not very clear as far what the actual problem is.