0
2

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の型ヒントマスター: mypy活用とジェネリクスの高度な使用法

Last updated at Posted at 2024-07-23

はじめに

Pythonの型ヒントは、コードの品質と可読性を向上させる強力なツールです。本記事では、静的型チェッカーであるmypyの活用方法と、ジェネリクスを使用した高度な型ヒントの実装について解説します。

目次

  1. mypyの基本
  2. mypyの高度な設定
  3. ジェネリクスの基本
  4. ジェネリクスの高度な使用法
  5. まとめ

mypyの基本

mypyは、Pythonの静的型チェッカーです。コードを実行せずに型の整合性をチェックできます。

インストールと基本的な使用方法

pip install mypy

使用例:

# example.py
def greet(name: str) -> str:
    return f"Hello, {name}!"

result = greet(42)  # 型エラー

mypyを実行:

mypy example.py

出力:

example.py:4: error: Argument 1 to "greet" has incompatible type "int"; expected "str"

image.png

mypyの高度な設定

mypyの設定ファイル(mypy.ini)を使用することで、より細かな型チェックが可能になります。

# mypy.ini
[mypy]
disallow_untyped_defs = True
strict_optional = True
warn_return_any = True
warn_unused_ignores = True

これらの設定により、より厳密な型チェックが可能になります。

ジェネリクスの基本

ジェネリクスを使用すると、型に依存しない汎用的なコードを書くことができます。

from typing import TypeVar, List

T = TypeVar('T')

def first_element(lst: List[T]) -> T:
    if lst:
        return lst[0]
    raise IndexError("List is empty")

# 使用例
int_list = [1, 2, 3]
str_list = ["a", "b", "c"]

print(first_element(int_list))  # 1
print(first_element(str_list))  # "a"

ジェネリクスの高度な使用法

制約付きジェネリクス

特定の型に制約をつけたジェネリクスを定義できます。

from typing import TypeVar, List

Number = TypeVar('Number', int, float)

def sum_list(lst: List[Number]) -> Number:
    return sum(lst)

print(sum_list([1, 2, 3]))  # 6
print(sum_list([1.5, 2.7, 3.2]))  # 7.4
# print(sum_list(["a", "b", "c"]))  # エラー

ジェネリッククラス

ジェネリクスを使用してクラスを定義することもできます。

from typing import Generic, TypeVar

T = TypeVar('T')

class Box(Generic[T]):
    def __init__(self, content: T):
        self.content = content

    def get_content(self) -> T:
        return self.content

int_box = Box[int](42)
str_box = Box[str]("Hello")

print(int_box.get_content())  # 42
print(str_box.get_content())  # "Hello"

まとめ

image.png

Pythonの型ヒントとmypyを活用することで、より安全で読みやすいコードを書くことができます。ジェネリクスを使用することで、型に依存しない柔軟なコードを実装できます。これらのテクニックを習得することで、Pythonプログラミングのスキルを一段階上げることができるでしょう。

参考資料:

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?