Skip to content

Quantity API #23

Open
Open
@andrewgsavage

Description

@andrewgsavage

There has been some interest in a Quantity or Units API, similar to the array API standard.

hgrecco/pint#2101
astropy/astropy#8210
astropy/astropy#13460
astropy/astropy-APEs#91
https://pydims.github.io/pydims/developer/index.html

A Quantity API that standardises methods and attributes would make it easier to write code that supports multiple unit libraries. At present this is difficult and has lead to multiple integration packages being written to support units, eg pint-xarray and xarray-quantity.

Although the implementations of the unit libraries differ, they share the same core concepts of a Quantity and Unit. I echo the suggestion to create a Protocol, similiar to https://github.com/nstarman/units/tree/main/src/units/api However I think the first version of a Quantity API should have a smaller scope to make it easier to agree on and adopt.

At time of writing, support for the array api is in development. An initial implementation suggests standardising the following methods would allow an implementation to be used across multiple libraries.

Quantity.__init__(value, units)
Quantity.units / .unit
Quantity.magnitude / .value
Quantity.m_as(units) / .to_value
Unit.__pow__
Unit.__add__
Unit.__sub__
Unit.__mul__
Unit.__div__

Unit.__sub__ is used to get a delta unit, eg for temperature. Quantity.__sub__ could be used instead.

That's not many functions at all!
pint-pandas looks like it'd also need Unit(unit_string) and I've used Quantity.to(Unit).magnitude instead of .m_as. It also uses pint's errors and formatting but that's quite complex.

Equally I think this could be easy for the unit libraries to implement; for example pint would add Quantity.value that returns Quantity.magnitude, astropy would add Quantity.units that returns Quantity.unit and so on (attribute names tbd!), there's no need to depreciate the current attributes. It would be good to change documentation to use the standardised methods to encourage their use.

I'm not against standardising other classes or methods like Systems or <<, I'd just rather do so in a future version.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions