单位感知类型批注#

Python支持使用类型语法的静态类型分析 PEP 484 。有关类型提示、函数批注和其他相关语法的详细指南,请参见 Real Python Guide 。下面我们将介绍如何使用数量类型提示和注释,并包括有关相关单位的元数据。

我们假设有以下导入内容:

>>> import typing as T
>>> import astropy.units as u
>>> from astropy.units import Quantity

土方类型注释#

A Quantity 可用作类型批注::

>>> x: Quantity = 2 * u.km

或作为函数注释。::

>>> def func(x: Quantity) -> Quantity:
...     return x

保留单位#

虽然上面的批注对于注释值的类型很有用,但它并没有告诉我们 Quantity :单位。

可以通过语法包括单元信息 Quantity[unit or "physical_type", shape, numpy.dtype] .:

>>> Quantity[u.m]
typing.Annotated[astropy.units.quantity.Quantity, Unit("m")]
>>>
>>> Quantity["length"]
typing.Annotated[astropy.units.quantity.Quantity, PhysicalType('length')]

看见 typing.Annotated 要解释一下 Annotated

这些函数也可用于函数

>>> def func(x: Quantity[u.kpc]) -> Quantity[u.m]:
...     return x << u.m

多个注解#

多数量、多单位意识 Quantity 使用以下工具支持批注 UnionOptional (包括 | 操作)。

>>> Quantity[u.m] | None
typing.Optional[typing.Annotated[astropy.units.quantity.Quantity, Unit("m")]]
>>>
>>> Quantity[u.m] | Quantity["time"]
typing.Union[typing.Annotated[astropy.units.quantity.Quantity, Unit("m")],
             typing.Annotated[astropy.units.quantity.Quantity, PhysicalType('time')]]

类型批注模块#