0
1

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関数設計の基本と応用:型ヒント・with構文・モジュール化まで

Last updated at Posted at 2025-10-18

:pencil: はじめに

この内容は、Pythonで簡単なスクリプトを書けるようになった方や、print()for文を使った処理は問題なく書けるというレベルの方を対象にしています。
「関数は使ったことがあるけど、定義の仕方や型ヒント、再利用の設計までは自信がない」という方に向けて、Python関数の基本構文から、実務でも役立つ応用ポイントまでを記載しています。

関数定義

関数定義の基本構文

def 関数名(): で始まり、インデントでブロックを表現する

def greet(name):
    print("Hello", name)

戻り値ありの関数

def add(a, b):
    return a + b
  • return:戻り値を返す
  • 型宣言は任意(後述の型ヒントで明示可能)

型ヒント付き

def add(a: int, b: int) -> int:
    return a + b
  • a: int:引数の型
  • -> int:戻り値の型
  • 型チェックや補完に有効

デフォルト引数

def greet(name="hoge"):
    print("こんにちは", name)
  • name="hoge":デフォルト引数

可変長引数

def log_all(*args):
    for item in args:
        print(item)
  • *args: 可変長引数

モジュール化と再利用

関数は .py ファイルにまとめておくことで、他のスクリプトから import して再利用できます:

db.py
def get_db_connection():
    ...
insert.py
from db import get_db_connection

with 構文

with は「リソースの取得と解放を安全に管理するための構文。C言語でいうところのfopen → 処理 → fclose()のようなながれを自動で安全に行ってくれる仕組み
利点まとめ

観点 メリット
安全性 例外が起きても後処理が保証される
可読性 try-finallyを省略できる

withを使った基本構文

with オブジェクト as 変数:
    処理

この「オブジェクト」は__enter__()__exit__()を持つ特殊なクラス(コンテキストマネージャ)

ファイル操作の例

with open("data.txt", "r", encoding="utf-8") as f:
    content = f.read()
  • open()がファイルを開く
  • with によって f.close()が自動で呼ばれる(例外が起きても安全)

DB接続の例(psycoge2)

from db import get_db_connection

with get_db_connection() as conn:
    cur = conn.cursor()
    cur.execute("SELECT * FROM table")
    conn.commit()
    cur.close()
  • get_db_connection()@contextmanagerで定義された関数
  • conn.close()が自動で呼ばれる

@contextmanager

@contextmanagerは「with構文で使える関数」を作るための仕組み

使い方の基本構文

from contextlib import contextmanager
@contextmanager
def open_resource():
    print("準備中")      # ← 前処理
    yield "リソース"     # ← 処理対象を返す
    print("後処理中")    # ← 後処理(必ず実行される)

使い方:

with open_resource() as r:
    print("使ってます →", r)

出力:

準備中
使ってます → リソース
後処理中

:white_check_mark:仕組み

|構成|役割|
|@contextmanager|デコレータ:関数を「with対応」に変換|
|yield|処理対象を返す(withasに渡る)|
|try-finally|yieldの前後に書くと安全性が高まる|

実用例:DB接続を安全に管理

@contextmanager
def get_db_connection():
    conn = psycopg2.connect(...)
    try:
        yield conn
    finally:
        conn.close()

使い方:

with get_db_connection() as conn:
    cur = conn.cursor()
    ...
  • conn は yield されたオブジェクト
  • with を抜けると conn.close() が自動で呼ばれる

おわりに

本記事では、Python関数の基本構文から、型ヒント・デフォルト引数・可変長引数・モジュール化・with構文まで、関数設計の基礎と応用を整理しました。

「とりあえず動く」から「構造的に再利用できる」関数設計へ──Python初心者でも納得感を持ってステップアップできる内容になっていれば幸いです。

今後は、以下のようなテーマについても整理していく予定です:

  • パッケージ化と名前空間設計:複数モジュールを構造的に管理する方法
  • 例外処理と関数設計の責務分離:安全性と可読性を両立するエラーハンドリング

:paperclip: 関連リンク

本記事と関連する内容を、以下の記事で詳しく解説しています。必要に応じて併せてご参照ください:

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?