2
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?

【Python】エラー「TypeError: unsupported operand type(s) for |: '_GenericAlias' and 'NoneType'」の原因とは

2
Posted at

概要

pytestを実行すると以下のエラーに。

def sample_func(self, token: str) -> List[Dict[str, str]] | None:
E TypeError: unsupported operand type(s) for |: '_GenericAlias' and 'NoneType'

他の環境では問題なかったので、自分のローカル環境に何か問題があるよう。
ということで調査。

原因

実施したテストコードの中で呼んでいる関数に以下のような型ヒントを使っている箇所がありました。

def sample_func(self, token: str) -> List[Dict[str, str]] | None:

これについて、

上記stackoverflowでは、str | None という「|」による型の合成は、python3.10以降で使用されるもの、とある。

確かにPython 3.10 以降では型ヒントでいくつか改善があったと聞いたことがあります。
↓とか

ということで、ローカル環境をpython3.12にアップデートして再度テストを実施したところ、エラーがなくなりました。

以上!

2
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
2
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?