LoginSignup
9
10

More than 5 years have passed since last update.

Python3 の少し複雑な型ヒントの具体例

Posted at

Python3.5から導入されたうれしい型ヒント機能ですが、「このような型はどうやって定義すれば?」と思うことがあったので、メモしました。
(ジェネリクスについては難しいので、今回はなしで・・)

str または bytes のようなORの型ヒント

Union[str, bytes] のように Union を使えば可能です。

def func(src: typing.Union[str, bytes]):
    ...

ファイルのように扱える (file-like object) の型ヒント

# file-like object型ヒント
def func(file: typing.IO):
    ...

# テキストであることを明示
def func_text(file: typing.TextIO):
    ...

# バイナリであることを明示 
def func_binary(file: typing.BinaryIO):
    ...

C の typedef のように別名をつける(型エイリアス)

import typing 

# typing module の中にあるものは代入で別名をつけることができます
AppSetting = typing.Dict[str, dict]

継承した型をつくる (NewType)

型エイリアスは別名をつけるだけですが、NewTypeはサブクラスのような扱いになります

# str, int のようなビルトインの型でも可能です
UserID = typing.NewType('UserID', int)

参考リンク

9
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
10