Types
Provide Pydantic-compatible annotations and fields for validating and serializing AstroPy unit-aware "quantities"
- class QuantityAnnotation(unit: str, *, description: str = '', decimals: int | None = None, min_shape: Tuple[int, ...] | None = None, max_shape: Tuple[int, ...] | None = None, ge: Quantity | str | None = None, gt: Quantity | str | None = None, le: Quantity | str | None = None, lt: Quantity | str | None = None, ser_mode: Literal['str', 'dict'] | None = None, strict: bool = True)[source]
Bases:
objectPydantic compatible annotation for validating and serializing AstroPy Quantity fields. Loosely adapted from pint-quantity by Tyler Hughes <tylerxh111+git@proton.me>
Examples
>>> from typing import Annotated >>> from astropy import units as u >>> from pydantic import BaseModel >>> from .quantity import QuantityAnnotation
>>> class Coordinates(BaseModel): ... latitude: Annotated[ ... u.Quantity, QuantityAnnotation("deg", ge=-90.*u.deg, le=90.*u.deg) ... ] ... longitude: Annotated[u.Quantity, QuantityAnnotation("deg")] ... altitude: Annotated[u.Quantity, QuantityAnnotation("km")]
>>> # The following instantiation validates >>> coord = Coordinates( ... latitude="39.905705 deg", ... longitude="-75.166519 deg", ... altitude="12 m" ... )
>>> coord Coordinates(latitude=<Quantity 39.905705 deg>, longitude=<Quantity -75.166519 deg>, altitude=<Quantity 0.012 km>)
>>> f"{coord!r}" 'Coordinates(latitude=<Quantity 39.905705 deg>, longitude=<Quantity -75.166519 deg>, altitude=<Quantity 0.012 km>)'
>>> coord.model_dump() {'latitude': <Quantity 39.905705 deg>, 'longitude': <Quantity -75.166519 deg>, 'altitude': <Quantity 0.012 km>}
>>> coord.model_dump(mode="json") {'latitude': '39.905705 deg', 'longitude': '-75.166519 deg', 'altitude': '0.012 km'}
>>> coord.model_dump_json() '{"latitude":"39.905705 deg","longitude":"-75.166519 deg","altitude":"0.012 km"}'
>>> # The following instantiation does not validate >>> coord = Coordinates( ... latitude="99.905705 deg", ... longitude="-75.166519 deg", ... altitude="12 m" ... ) Traceback (most recent call last): ... pydantic_core._pydantic_core.ValidationError: 1 validation error for Coordinates latitude Value error, greater than 90.0 deg [type=value_error, input_value='99.905705 deg', input_type=str] For further information visit https://errors.pydantic.dev/2.7/v/value_error
- Parameters:
unit (str) -- The unit type of the Pydantic field (e.g., "m", or "deg"). All input units must be convertible to this unit.
description (str, optional) -- Description string.
decimals (int, optional) -- Maximum number of decimals for the serialization of quantities.
min_shape (tuple[int], optional) -- Minimum number of vector components on each axis.
max_shape (tuple[int], optional) -- Maximum number of vector components on each axis.
ser_mode (Literal["str", "dict"], optional) -- The mode for serializing the field; either "str" or "dict". By default, in Pydantic's "python" serialization mode, fields are serialized to a Quantity; in Pydantic's "json" serialization mode, fields are serialized to a str.
strict (bool, optional) -- Forces users to specify units; on by default. If disabled, a value without units - provided by the user - will be treated as the base units of the QuantityUnit.
- validate(v: dict | str | Number | Quantity, info: ValidationInfo | None = None) Quantity[source]
Validate Quantity.
- Parameters:
- Returns:
v (~astropy.units.Quantity) -- Validated Quantity with the correct units.
- Raises:
ValueError -- exception: An error occurred validating the specified value. It is raised if any of the following occur: - A dict is received and the keys "value" and "units" do not exist. - There are no units provided. - Provided units cannot be converted to base units. - An unknown unit was provided. - An unknown type for value was provided.
TypeError -- exception: An error occurred from unit registry or unit registry context. It is not propagated as a pydantic.ValidationError because it does not stem from a user error.
- serialize(v: Quantity, info: SerializationInfo | None = None, *, to_json: bool = False) dict | str | Quantity[source]
Serialize Quantity.
- Parameters:
v (Quantity) -- Quantity that should be serialized.
info (pydantic.core_schema.SerializationInfo, optional) -- Serialization info provided by the Pydantic schema.
to_json (bool, optional) -- Whether or not to serialize to a json convertible object. Useful if using QuantityUnit as a utility outside of Pydantic models.
- Returns:
quantity (str) -- The serialized Quantity.
- AnnotatedQuantity(default: Quantity | str | None = None, unit: str | None = None, short: str | None = None, description: str = '', decimals: int | None = None, min_shape: Tuple[int, ...] | None = None, max_shape: Tuple[int, ...] | None = None, ge: Quantity | str | None = None, gt: Quantity | str | None = None, le: Quantity | str | None = None, lt: Quantity | str | None = None) Any[source]
Pydantic pseudo-field for validating and serializing AstroPy Quantities.
Examples
>>> from pydantic_settings import BaseSettings >>> from .quantity import AnnotatedQuantity
>>> class Settings(BaseSettings): ... size: AnnotatedQuantity( ... short='S', ... description="an arbitrary length", ... default=10. * u.m, ... ge=1. * u.micron, ... lt=1. * u.km ... )
>>> # The following instantiation validates >>> s = Settings(size="3. cm")
>>> s Settings(size=<Quantity 0.03 m>)
>>> f"{s!r}" 'Settings(size=<Quantity 0.03 m>)'
>>> s.model_dump() {'size': <Quantity 0.03 m>}
>>> s.model_dump(mode="json") {'size': '0.03 m'}
>>> s.model_json_schema() {'additionalProperties': False, 'properties': {'size': {'default': '10.0 m', 'description': 'an arbitrary length', 'exclusiveMaximum': '1.0 km', 'minimum': '1.0 micron', 'physType': 'length', 'short': 'S', 'title': 'Size', 'type': 'string'}}, 'title': 'Settings', 'type': 'object'}
>>> # The following instantiation does not validate >>> s = Settings(size="4 deg") Traceback (most recent call last): ... pydantic_core._pydantic_core.ValidationError: 1 validation error for Settings size Value error, 'deg' (angle) and 'm' (length) are not convertible [type=value_error, input_value='4 deg', input_type=str] For further information visit https://errors.pydantic.dev/2.8/v/value_error
- Parameters:
unit (str, optional) -- Unit for quantity (overrided by default unit if provided).
short (str, optional) -- shortcut for keyword.
description (str, optional) -- Description string.
decimals (int, optional) -- Maximum number of decimals for the serialization of quantities.
min_shape (tuple[int], optional) -- Minimum number of vector components on each axis.
max_shape (tuple[int], optional) -- Maximum number of vector components on each axis.
- str_to_quantity_array(s: str) Quantity | None[source]
Convert string to Astropy "units" Quantity array
Notes
Currently limited to "well-formed", 1D arrays.
Examples
>>> from .quantity import str_to_quantity_array
>>> str_to_quantity_array("[3.14, 1e+06] m") <Quantity [3.14e+00, 1.00e+06] m>
- Parameters:
s (str) -- Input string.
- Returns:
v (~astropy.units.Quantity) -- Astropy units Quantity object.
Provide Pydantic-compatible annotations and annotated types for enhanced string validation and serialization.
- class StrAnnotation(*, description: str = '', min_length: int | None = None, max_length: int | None = None, pattern: Pattern | None = None, valid_list: list[str] | None = None)[source]
Bases:
objectPydantic compatible annotation for validating and serializing strings (the original Pydantic 2.x string fields only support Rust Regex).
Examples
>>> from typing import Annotated >>> from pydantic import BaseModel >>> from .string import StrAnnotation
>>> class Person(BaseModel): ... firstname: Annotated[str, StrAnnotation(pattern=r"[A-Z][a-z]*")] ... lastname: Annotated[str, StrAnnotation(pattern=r"[A-Z][a-z]*")]
>>> # The following instantiation validates >>> user = Person(firstname="Emmanuel", lastname="Bertin")
>>> # The following instantiation does not validate >>> user = Person(firstname="emmanuel", lastname="Bertin") Traceback (most recent call last): ... pydantic_core._pydantic_core.ValidationError: 1 validation error for Person firstname Value error, string does not match [A-Z][a-z]* pattern [type=value_error, input_value='emmanuel', input_type=str] For further information visit https://errors.pydantic.dev/2.8/v/value_error
- Parameters:
- validate(s: str, info: ValidationInfo | None = None) str[source]
Validate str.
- Parameters:
s (str) -- String that should be validated.
info (ValidationInfo, optional) -- The validation info provided by the Pydantic schema.
- Returns:
s (str) -- Validated string.
- Raises:
ValueError -- exception: An error occurred validating the specified string. It is raised if any of the following occur: - the provided string did not match the pattern. - An unknown type was provided for the string.
- AnnotatedStr(default: str, short: str | None = None, description: str = '', min_length: int | None = None, max_length: int | None = None, pattern: Pattern | None = None, valid_list: list[str] | None = None) Any[source]
Pydantic pseudo-field for validating and serializing strings (the original Pydantic 2.x string fields only support Rust Regex).
Examples
>>> from pydantic_settings import BaseSettings >>> from .string import AnnotatedStr
>>> class Person(BaseSettings): ... firstname: AnnotatedStr( ... short='f', ... description="First name.", ... default="Unknown", ... min_length=1, ... pattern=r"[A-Z][a-z]*" ... ) ... lastname: AnnotatedStr( ... short='l', ... description="Last name.", ... default="Unknown", ... min_length=1, ... pattern=r"[A-Z][a-z]*" ... )
>>> # The following instantiation validates >>> user = Person(firstname="Emmanuel", lastname="Bertin")
>>> # The following instantiation does not validate user = Person(firstname="emmanuel", lastname="Bertin") Traceback (most recent call last): ... pydantic_core._pydantic_core.ValidationError: 1 validation error for Person firstname Value error, string does not match [A-Z][a-z]* pattern [type=value_error, input_value='emmanuel', input_type=str] For further information visit https://errors.pydantic.dev/2.8/v/value_error
- Parameters:
short (str, optional) -- shortcut for keyword
description (str, optional) -- Description string.
min_length (int, optional) -- Minimum string length.
max_length (int, optional) -- Maximum string length.
pattern (Pattern, optional) -- Regular expression for validation.
valid_list (list[str], optional) -- List of validating strings.