# PythonのEllipsis(...)とtype hints

## この記事で書くこと

1. pythonのEllipsisとは
2. Ellipsisのtype hintsでの使用例

## 前提知識

1. Pythonのtype hintsについての簡単な知識
    1. スタブファイルが何者かなど
2. Pythonについての基本的な知識
3. 型システムについての基本的な理解

## 記事作成の動機

1. スタブファイルで多用されているellipsisの意味がわからなかった

例えばfunctoolsモジュールのpartialクラスのスタブファイル

```python
class partial(Generic[_T]):
    func = ...  # type: Callable[..., _T]
    args = ...  # type: Tuple[Any, ...]
    keywords = ...  # type: Dict[str, Any]
    def __init__(self, func: Callable[..., _T], *args: Any, **kwargs: Any) -> None: ...
    def __call__(self, *args: Any, **kwargs: Any) -> _T: ...
```

ナンノコッチャ

2. ellipsisとtype hintsについての記事がpep484くらいしか無い

## Ellipsisとは

1. `...`の3点ドットで表されるシングルトンオブジェクト
    1. グーグラビリティが低い
2. 「ellipsis」とは省略記号という意味
3. python的にはなにか有るが、とりあえず省略していることを表す
    1. これが`None`との違い
4. 文でなく式、つまり値として利用できる
    1. これが`pass`との違い

## Type Hintsでの使用例

### `Callable`での引数リスト型の省略

[PEP484](https://www.python.org/dev/peps/pep-0484/#callable)  
[翻訳記事](https://qiita.com/t2y/items/f95f6efe163b29be59af#%E5%91%BC%E3%81%B3%E5%87%BA%E3%81%97%E5%8F%AF%E8%83%BD%E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF%E3%83%88)

#### `Callable`型

コールバック関数のように引数に関数を渡したときの型。

from typing import Callable

```python
def feeder(get_next_item: Callable[[], str]) -> None:
    # Body

def async_query(on_success: Callable[[int], None],
                on_error: Callable[[int, Exception], None]) -> None:
    # Body
```

#### `Callable`の引数リストの型の省略

コールバック関数の戻り値のみを記載したいときがある。  
その場合、引数リストを`...`で置き換える。

```python
def partial(func: Callable[..., str], *args) -> Callable[..., str]:
    # Body
```

### スタブファイルでデフォルト引数が存在することを示す

[PEP484](https://www.python.org/dev/peps/pep-0484/#arbitrary-argument-lists-and-default-argument-values)  
[翻訳記事](https://qiita.com/t2y/items/f95f6efe163b29be59af#%E3%83%87%E3%83%95%E3%82%A9%E3%83%AB%E3%83%88%E5%BC%95%E6%95%B0%E3%81%AE%E5%80%A4)

スタブファイルである関数の引数にデフォルト値が存在することは定義しても、その値までは定義したくないことがある。  
その場合デフォルト値を`...`で代用する。

```python
def foo(x: AnyStr, y: AnyStr = ...) -> AnyStr: ...
```

引数`y`はデフォルト値として、`""`、`b""`、`None`のいずれも適切でなく、`...`が省略の意味として適切。

### スタブファイルで関数本体を示す

[PEP484](https://www.python.org/dev/peps/pep-0484/#stub-files)  
[翻訳記事](https://qiita.com/t2y/items/f95f6efe163b29be59af#%E3%82%B9%E3%82%BF%E3%83%96%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB)

スタブファイルの役目は関数やクラスのインターフェイスを示すことである。  
その場合、関数の中身は記述する必要は無く、`...`で記述する。

```python
    def __init__(self, func: Callable[..., _T], *args: Any, **kwargs: Any) -> None: ...
```

### Typingモジュールの`Tuple`型で任意の長さであることを示

[PEP484](https://www.python.org/dev/peps/pep-0484/#the-typing-module)  
[翻訳記事](https://qiita.com/t2y/items/f95f6efe163b29be59af#typing-%E3%83%A2%E3%82%B8%E3%83%A5%E3%83%BC%E3%83%AB)

型として、長さを定めない`Tuple`型を指定したいときがある。  
その場合`Tuple[int, ...]`でアノテーションする。  
これはすべての要素が`int`で長さが任意のタプルを表す。

### python2のType Hintsでの関数の引数型の省略

[PEP484](https://www.python.org/dev/peps/pep-0484/#suggested-syntax-for-python-2-7-and-straddling-code)

### python2での型アノテーション

python2では型アノテーション機能が無い。  
しかし、型アノテーション自体はコメントを使って書くことが推奨されている。

# python2

```python
def embezzle(self, account, funds=1000000, *fake_receipts):
    # type: (str, int, *str) -> None
    """Embezzle funds from account using fake receipts."""
    <関数本体をここに書く>

これは以下のpython3コードと等価。
```

# python3

```python
def embezzle(self, account: str, funds: int = 1000000, *fake_receipts: str) -> None:
    """Embezzle funds from account using fake receipts."""
    <関数本体をここに書く>
```

### 戻り値のみ記載したい場合の省略

引数の型がまだ決定しておらず、戻り値のみ型を書きたいことがある。  
そのとき、引数の型を`...`で書く。

```python
def send_email(address, sender, cc, bcc, subject, body):
    # type: (...) -> bool
    """Send an email message.  Return True if successful."""
```

### 引数が長いときの型を書く場所の分割

関数に引数が非常に多いとき、それらの型をコメントで書く場合コードが醜くなる。  
その場合、引数の型と、戻り値の型を書く場所を別にするとスッキリする。
```python
def send_email(address,     # type: Union[str, List[str]]
               sender,      # type: str
               cc,          # type: Optional[List[str]]
               bcc,         # type: Optional[List[str]]
               subject='',
               body=None    # type: List[str]
               ):
    # type: (...) -> bool
    """Send an email message.  Return True if successful."""
```
