0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

beartypeについて

0
Posted at

概要

pythonの型ヒントを強化するパッケージ。
実行時に型チェックを行うデコレータを提供する。

詳細な情報は以下のリンクを参照

インストール

beartypeは組み込みパッケージではなく、別途インストールする必要がある

pip install beartype

サブパッケージ

beartypeパッケージの下にいくつかのサブパッケージが存在する。

サブパッケージ 概要
beartype メインAPI (@beartypeの提供)
beartype.claw importをフックするAPI
beartype.door Decidedly Object-Oriented Runtime-checker (DOOR)関連API
beartype.roar 例外やワーニング関連API
beartype.vale バリデータAPI

元情報はこちら

簡単な利用例

beartypeは関数やクラスに適用するデコレータであり、単純な型定義や変数などに対しての利用は想定していない。

関数に適用する例

まず大前提として、pythonの型ヒントは、他言語の型とは異なり実行時にエラーにならない。

beartypeを付与しない場合、add("1", "2")はIDE上でエラーとして検出されるが、正常に実行される。

def add(x: int, y: int) -> int:
    return x + y

print(add(1, 2)) # 3
print(add("1", "2")) # "12"

beartypeを付与した場合、実行時に例外が出力される。

from beartype import beartype
@beartype
def add(x: int, y: int) -> int:
    return x + y

print(add(1, 2)) # 3
print(add("1", "2")) # エラー

Annotatedとの連携

Annotatedを利用すると、自作の型にメタ情報を付与できる。

from beartype.vale import Is
# 型ヒントに制約を追加
# - 文字列の長さが1以上4以下
SmallName = Annotated[str, Is[lambda s: 1 <= len(s) <= 4]]

beartypeを付与しない場合、上記のメタ情報(文字列長が1~4の制約)を無視して利用してもエラーなどにはならない。

def name_to_str(name: SmallName) -> str:
    return name

print(name_to_str("word")) # "word"
print(name_to_str("double")) # "double"

beartypeを付与すると、Annotatedで定義した制約に引っかかるのでエラーになる。

@beartype
def name_to_str(name: SmallName) -> str:
    return name

print(name_to_str("word")) # "word"
print(name_to_str("double")) # エラー

検出される例外

検出される例外は以下のページにまとまっているので、必要に応じて利用する。

上述の例外が発生するケースは、いずれも BeartypeCallHintViolationが発生する。

try:
    print(add("1", "2")) # エラー
except BeartypeCallHintViolation as e:
    print('add("1", "2") raised BeartypeCallHintViolation:', e)

その他注意点

  • 実行時に型チェックが走るので、導入すると実行速度は低下する可能性がある
  • 組み込みパッケージではないので、プロジェクトへ導入する際にはメリットとデメリットを比較して慎重に導入する必要がある

終わりに

beartypeについて調べたので、簡単にまとめました。
pythonの通常の型ヒントで十分なケースがほとんどだと思うので、導入する際には、beartypeで何を実現したいのか明確にしておく必要があるかと思います。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?