astropy/astropy — pull request #1383 by alexrudy (2013-08-28 00:48:08+00:00)
Title: Quantity format

Caveat: I haven't discussed this anywhere yet. It probably belongs on the mailing list.

From the mailing list, I suggested, then learned about the [__format__ special method](http://docs.python.org/3.3/reference/datamodel.html#object.__format__). I didn't know it existed. However, I think it is a nice way to control the formatting of quantities. Basically, it takes the format specifier, and if it is a normal python specifier, passes it to the quantity's ``.value`` attribute. If the format specifier contains two items, the first is used to format the specifier, and the second is used to format the unit.

My intent is to implement something similar for units, but with additional format type specifiers, like ``l`` to produce latex output and ``u`` to produce unicode output.

Specific Things to Try:

```
In [1]: import astropy.units as u

In [2]: q = 10.5 * u.km

In [3]: "{}".format(q)
Out[3]: '10.5 km'

In [5]: "{:.0f}".format(q)
Out[5]: '10 km'

In [3]: "{:+5.0f~>10s}".format(q)
Out[3]: ' +10~ km'

```
- Format specifiers (like ``0.3f``) are re-interpreted for quantity:
- Single specifiers are passed to Quantity.value
- The first of multiple specifiers is passed to Quantity.value
- The character after the first specifier is used to separate the value and unit.
- Remaining specifiers are passed to the unit.

Some potential considerations:
- I haven't implemented an ``l`` format code here, for latex like formatted values... maybe that would be a good idea?
- The behavior of this, and other functions (like ``_repr_latex_``) gets trickier when the underlying value is an ndarray
- Implicitly using the character after first specifier as the separator, and any remaining characters as units might not be always correct.
- If we implement uncertainties, there isn't really a great way to support them with this current syntax... maybe first specifier for value, second for uncertainty, third for units?
- Please check my regular expressions!