Commit 0515436f authored by BO ZHANG's avatar BO ZHANG 🏀
Browse files

add optional and union cases

parent c005808c
Loading
Loading
Loading
Loading
Loading
+14 −0
Original line number Diff line number Diff line
%% Cell type:markdown id:63584611-70c6-45e4-acfb-9bda5204fda0 tags:

# How to do Python type annotation

%% Cell type:markdown id:7cc03b6e-5bc4-47e4-b42c-3a22eb11539b tags:

## built-in types

%% Cell type:code id:bfaf414a-40f8-4830-8be4-65f43a03d513 tags:

``` python
a: int = 8 # 整数型标注
b: float = 1.23 # 浮点型标注
c: bool = True # 布尔型标注
d: tuple = (1, 2) # 元组型标注
e: tuple[int, float] = (1, 2.34) # 限定类型和元素个数的元组标注
f: tuple[int, ...] = (1, 2, 3, 4, 5) # 限定类型但不定元素个数的元组型标注
g: list = [1, 2, 3] # 一般的列表型标注
h: list[int] = [1, 2, 3] # 对列表型来说不需要标元素个数,但可以明确要求元素类型
```

%% Cell type:markdown id:ba646556-0bfa-4a8f-8767-9d76e5c44592 tags:

## `typing` 模块
对于一些内建类型来说是可以直接用内建类型来标注的,例如以下两句是相等的

%% Cell type:code id:8759dc5b-01e9-4583-ab27-114ea87315db tags:

``` python
l1: list[int] = [1, 2, 3]

from typing import List
l2: List[int] = [1, 2, 3]
```

%% Cell type:markdown id:8f2203cb-8e94-406e-b445-809d04f85e26 tags:

## Union, Optional和Any

- Union表示并集,Union[float, int]表示可以是float也可以是int
- Optional表示可选,Optional[int]表示可以是None也可以是int
- Any表示任意类型

%% Cell type:code id:3b323abd-7689-4abd-aa02-049b1de7bfcb tags:

``` python
fx0: Optional[int] = None
```

%% Output

    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
Cell     In[3], line 1
    ----> 1 x0: Optional[int] = None
    NameError: name 'Optional' is not defined

%% Cell type:markdown id:4906826b-2817-4a5b-b3ac-a993fa96b315 tags:

## numpy.typing
我们经常会用到numpy.ndarray进行科学计算,可以有以下几种标注方式:

1. 直接用np.ndarray进行标注, 此时不限定类型(dtype)

%% Cell type:code id:d93f8b14-5f88-4579-a671-1693d04ce144 tags:

``` python
import numpy as np

x1: np.ndarray = np.arange(10)
```

%% Cell type:code id:14b83562-b6c6-4873-8936-ad9d0c9c0e6f tags:

``` python
import numpy.typing as npt

x2: npt.NDArray = np.arange(10, dtype=float)
x3: npt.NDArray[np.int_] = np.arange(10, dtype=int)
x4: npt.NDArray[np.float_] = np.arange(10, dtype=float)
x5: npt.NDArray[np.float32] = np.arange(10, dtype=np.float32)
x6: npt.NDArray[np.bool_] = np.ones(10, dtype=bool)
x7: npt.NDArray[np.complex_] = np.ones(10, dtype=np.complex_)
```

%% Cell type:code id:cc6abe41-f8a1-4c9d-8deb-ba7dad66780f tags:

``` python
```