astropy/astropy — pull request #602 by mdboom (2013-01-03 19:02:28+00:00)
Title: Improve whitespace handling in astropy.unit.Unit FITS format string parsing?

I ran into this error:

```
In [81]: u.Unit('m / s')
ERROR: ValueError: Expected integer (at char 5) in 'm / s' [astropy.units.format.generic]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
in ()
----> 1 u.Unit('m / s')

/Users/deil/Library/Python/2.7/lib/python/site-packages/astropy/units/core.pyc in __call__(self, s, represents, format, register, doc, parse_strict)
735 f = unit_format.get_format(format)
736 try:
--> 737 return f.parse(s)
738 except ValueError as e:
739 if parse_strict == 'raise':

/Users/deil/Library/Python/2.7/lib/python/site-packages/astropy/units/format/generic.pyc in parse(self, s)
247 except p.ParseException as e:
248 raise ValueError("{0} in {1!r}".format(
--> 249 utils.cleanup_pyparsing_error(e), s))
250
251 def _get_unit_name(self, unit):

ValueError: Expected integer (at char 5) in 'm / s'
```

It took me a minute to figure out that the spaces are the problem, this works:
```
In [82]: u.Unit('m/s')
Out[82]: Unit("m / (s)")
```

After reading Section 4.3.1 on "Construction of units strings" of the [FITS Standard](http://fits.gsfc.nasa.gov/standard30/fits_standard30aa.pdf) I realize that the spaces in the `'m / s'` unit string is discouraged and thus the behaviour of the astropy parser is not a bug:
> Parentheses are used for symbol grouping and are strongly recommended whenever the order of operations might be subject to misinterpretation. A space character implies multiplication which can also be conveyed explicitly with an asterisk or a period. Therefore, although spaces are allowed as symbol separators, their use is discouraged.

However, @mdboom, I was wondering if the parsing error or maybe even the parsing behaviour could be improved here. It is a bit confusing that spaces in the unit string are OK in some cases:
```
u.Unit('m /s') # space before is OK
u.Unit('m / s1') # space before and after are OK if second operator has an exponent
u.Unit('m / (s)') # spaces before and after are OK if second operator is in parentheses
u.Unit('m / s1') # multiple spaces are OK where one space is OK
u.Unit('m s') # space only means multiply, i.e. u.Unit('m*s')
```
But spaces are not OK in these cases
```
u.Unit('m *s') # space before * not OK, was OK for /
u.Unit('m/ s') # space after / is not OK
```

Is it possible (with reasonable effort) to make `u.Unit('m / s')` work or give a more explicit error message that whitespace is the problem? If not, obviously feel free to just close this issue since this is not a bug.

Note that the CDS parser has it easy and gives
```
In [113]: u.Unit('m / s', format='cds')
ERROR: ValueError: CDS unit must not contain whitespace [astropy.units.format.cds]
```