hgrecco/pint — pull request #84 by jturner314 (2013-12-30 07:57:17+00:00)
Title: Improve Quantity's handling of operators with misc. object types

This pull request includes multiple commits with the following overall purposes:

- Add `decimal.Decimal` and the numpy numeric scalar types (subclasses of `numpy.number`) to the `NUMERIC_TYPES` list.

- Refactor the multiplication and division operators, similar to how the addition and subtraction operators are already done, to simplify the code.

- Make operator methods of Quantity return `NotImplemented` when they don't support the types of the arguments, as specified by the Python docs. (See [this page](http://docs.python.org/3/reference/datamodel.html#the-standard-type-hierarchy).) This is important so that Python can properly try fallback operations (e.g. using `__rmul__` on the other argument).

For example, with the old behavior, by changing the order of the multiplication of a Quantity and a Measurement, I can get a Quantity with a Measurement as its magnitude, or a Measurement that is the correct result:

->> x = 5 * ureg.meter
->> y = (7 * ureg.second).plus_minus(2)
->> str(x * y)
'(35 +/- 10) second meter'
->> type(x * y)
.Quantity'>
->> str(y * x)
'(35 +/- 10) meter * second'
->> type(y * x)

When Quantity's operations return `NotImplemented` as appropriate, Python handles such operations correctly:

->> x = 5 * ureg.meter
->> y = (7 * ureg.second).plus_minus(2)
->> str(x * y)
'(35 +/- 10) meter * second'
->> type(x * y)

->> str(y * x)
'(35 +/- 10) meter * second'
->> type(y * x)

- In order to implement the previous point, restrict magnitudes of `Quantity` objects to `NUMERIC_TYPES`. As you mentioned on issue #53, this has the disadvantage of requiring user-defined numeric types to be subclasses of `numbers.Number` or `decimal.Decimal`. However, I think it's worth the rare problems this would cause in order to provide proper operator functionality. One possibility would be to make `NUMERIC_TYPES` user-configurable so in the rare case that someone wants an additional numeric type, they can add it.

Note that only the last commit in this pull request passes all the unit tests. I can combine all of the commits into one if you'd like. Please let me know what you think and if I should make any further changes.