cf-xarray icon indicating copy to clipboard operation
cf-xarray copied to clipboard

add pretty formatting for units

Open dcherian opened this issue 2 years ago • 2 comments

Continuing from https://github.com/xarray-contrib/cf-xarray/pull/284#issuecomment-1018130308 (cc @keewis)

I see pint has a "pretty" formatting mode. Is there a way we can define the "pretty" string?

u = units.Unit("degrees_east")
f"{u:~P}"
degrees_east

EDIT: I see even pint doesn't do the pretty ° for "degrees"

u = units.Unit("degrees")
f"{u:P}"
degree

EDIT2: Should we define a Pcf formatter for our own pretty strings?

dcherian avatar Jan 21 '22 18:01 dcherian

I see even pint doesn't do the pretty ° for "degrees"

right, I was under the impression that it would do that for "~P", but that yields "deg", where for temperature units that would be e.g. "°C". If we look at the entry in default_en.txt, it's pretty obvious why:

degree = π / 180 * radian = deg = arcdeg = arcdegree = angular_degree

I think we have two options: use a different name (e.g. Pcf) or a new modifier. I don't think there is a way to add new modifiers at the moment, though, so that would need some time / work to implement in pint.

keewis avatar Jan 21 '22 19:01 keewis

Would it make sense to use : ~cf as the pretty / short version of cf and cf as the normal version?

An issue I see is that, some might find dangerous that we put °C in the units attribute of netCDFs. So, I could suggest:

from cf_xarray.units import units
u = units.Unit('degC')

f"{u:cf}" -> "degrees_Celsius"
f"{u:~cf}" -> "°C"

And similarly with latitude and longitude. (AFAIU, we only need to remove the ~ in the current code so that this proposition works).

Moreover, if hgrecco/pint#1486 is solved this way, we could also control how dimensionless units are printed out:

u = units.Unit("")

f"{u:cf}" -> "1"
f"{u:~cf}" -> ""

aulemahal avatar Mar 17 '22 15:03 aulemahal