Skip to content

Feature (discussion): Units #64

@tlambert03

Description

@tlambert03

Hi all. I know this library has focused mostly on validation constraints for pydantic, and I'll also copy the minimalist mission mentioned in the readme:

we expect that staying simple and covering only the most common use-cases will give users and maintainers the best experience we can. If you'd like more constraints for your types - follow our lead, by defining them and documenting them downstream!

I do, find the concept of a small no-dependency library that can be used to annotate things super useful as a way for multiple libraries to communicate information without tight coupling of types. I find myself specifically thinking about units these days (for example, in the context of device driver specifications, or other places where it's critical to indicate a quantity of something rather than a scalar).

I did a quick search through the issues here for "units" or "pint" or "astropy", and I also searched through the issues of those libraries for discussions of "annotated-types", but have not found a discussion so far (other than the obvious discussions of adding typing within the library itself). So, I just wanted to see if this is something that you here, or @hgrecco at pint, have thought of including? I'm thinking of something perhaps as simple as:

@dataclass(frozen=True)
class Quantity(BaseMetadata):
    """Quantity(unit='some_unit') implies that the value is a physical quantity with the specified unit.

    It can be used with any numeric type (`numbers.Number`).
    Interpretation of the unit string is left to the discretion of the consumer.
    """

    unit: str

# and in usage
@dataclass
class Parameters:
    width: Annotated[float, Quantity(unit='m')] = 1
    angle: Annotated[float, Quantity(unit='rad') = 0
    temperature: Annotated[float, Quantity(unit='celsius')] = 100
    weight: Annotated[float, Quantity(unit='kg') = 42

annotated_types itself would, of course, make no attempt to parse the unit string... that would be left to the end user, using libraries like pint.

Curious to hear your thoughts, @adriangb, @samuelcolvin, @hgrecco, et al.

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