Skip to content

Type annotation for creating custom types based on an AstroPy Quantity #55

@hettlage

Description

@hettlage

In addition to angles, which are covered by the aeonlib.types.Angle type, it might be helpful to support units in other fields as well, such as for an exposure time or a proper motion. Out of the box, this is not possible because Pydantic cannot validate or serialize AstroPy Quantity instances.

To allow for an easy creation of custom Pydantic types supporting units, one could add a type annotation, say AstropyQuantityTypeAnnotation, which might be used as follows:

from typing import Annotated, Union
from astropy import units as u
from astropy.units import Quantity
from aeonlib.salt.models.types import AstropyQuantityTypeAnnotation

ProperMotion = Annotated[
    Union[Quantity, float], AstropyQuantityTypeAnnotation(u.arcsec / u.year)
]
Wavelength = Annotated[
    Union[Quantity, float], AstropyQuantityTypeAnnotation(u.Angstrom)
]

from pydantic import BaseModel


class CelestialObject(BaseModel):
    proper_motion: ProperMotion
    peak_wavelength: Wavelength


# Create the same (up to rounding errors) object in three different ways.
# Note: 1 year = 8766 hours
object1 = CelestialObject(proper_motion=8766, peak_wavelength=5000)
object2 = CelestialObject(
    proper_motion=8766 * u.arcsec / u.year, peak_wavelength=5000 * u.Angstrom
)
object3 = CelestialObject(
    proper_motion=1 * u.arcsec / u.hour, peak_wavelength=5000 * u.nm
)

Would you consider a pull request which adds such a type annotation to the aeonlib.types module?

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

Status

Triage

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions