タイトル: ライブラリ
SEOタイトル: Python ライブラリ完全ガイド (標準 + 主要サードパーティ + pip)
| この記事の要点 |
- Python は 「電池付属 (batteries included)」: 標準ライブラリだけでも HTTP / JSON / 正規表現 / 並行処理が書ける
- 標準:
os / sys / json / re / datetime / collections / itertools / functools / pathlib / subprocess など 200+ モジュール - 主要サードパーティ: requests / numpy / pandas / scikit-learn / TensorFlow / PyTorch / Django / Flask / FastAPI / Selenium / BeautifulSoup
- インストールは
pip install パッケージ名。配布元は PyPI (Python Package Index) - 仕様は PEP (Python Enhancement Proposal)。標準は docs.python.org
|
Python ライブラリの全体像
Python のライブラリは大きく次の 3 階層に分かれます。
| 階層 | 例 | インストール |
| 組み込み (Built-in) | print, len, list, dict, 例外 | 不要 |
| 標準ライブラリ | os, sys, json, re, datetime, collections | Python に同梱 |
| サードパーティ | requests, numpy, django, fastapi, etc. | pip install |
標準ライブラリ: よく使うモジュール
| モジュール | 用途 | 主要 API |
os | OS 操作 | os.environ, os.getcwd(), os.makedirs() |
sys | インタプリタ操作 | sys.argv, sys.path, sys.exit() |
pathlib | パス操作 (推奨) | Path('a/b').read_text() |
json | JSON 読み書き | json.loads(), json.dumps() |
re | 正規表現 | re.search(), re.findall() |
datetime | 日時 | datetime.now(), timedelta |
collections | 追加コレクション | defaultdict, Counter, deque, namedtuple |
itertools | イテレータ操作 | chain, product, combinations, groupby |
functools | 関数ユーティリティ | lru_cache, partial, reduce, cached_property |
subprocess | 外部コマンド実行 | subprocess.run() |
logging | ログ | logging.getLogger() |
argparse | CLI 引数 | ArgumentParser() |
typing | 型ヒント | List, Optional, Union |
dataclasses | レコード型 | @dataclass |
asyncio | 非同期 I/O | async/await, gather() |
concurrent.futures | 並行実行 | ThreadPoolExecutor, ProcessPoolExecutor |
sqlite3 | SQLite | sqlite3.connect() |
urllib.request | HTTP (簡易) | urllib.request.urlopen() |
hashlib | ハッシュ | sha256(), md5() |
csv | CSV | csv.DictReader, csv.writer |
標準ライブラリのよく使う例
# pathlib: パス操作の現代標準
from pathlib import Path
p = Path('data/in.txt')
text = p.read_text(encoding='utf-8')
Path('out').mkdir(exist_ok=True)
for f in Path('logs').glob('*.log'):
print(f.stat().st_size)
# collections.Counter: 出現回数集計
from collections import Counter
words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']
Counter(words).most_common(2) # [('apple', 3), ('banana', 2)]
# functools.lru_cache: メモ化
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n: int) -> int:
return n if n < 2 else fib(n-1) + fib(n-2)
# datetime + timedelta
from datetime import datetime, timedelta
tomorrow = datetime.now() + timedelta(days=1)
# json: 設定ファイル読み書き
import json
config = json.loads(Path('config.json').read_text())
Path('config.json').write_text(json.dumps(config, indent=2, ensure_ascii=False))
主要サードパーティライブラリ
Web / HTTP
| ライブラリ | 用途 |
requests | シンプルな HTTP クライアント |
httpx | 非同期対応 HTTP (requests 互換) |
aiohttp | asyncio ネイティブの HTTP |
Django | フルスタック Web フレームワーク |
Flask | マイクロ Web フレームワーク |
FastAPI | 型ヒント駆動の非同期 Web (OpenAPI 自動生成) |
Selenium | ブラウザ自動操作 |
Playwright | モダンなブラウザ自動操作 |
BeautifulSoup (bs4) | HTML / XML パーサ |
lxml | 高速 XML / HTML |
scrapy | スクレイピングフレームワーク |
データ分析 / 機械学習
| ライブラリ | 用途 |
numpy | 多次元配列、ベクトル化計算 |
pandas | 表形式データ (DataFrame) |
matplotlib | グラフ描画 |
seaborn | 統計グラフ (matplotlib ラッパ) |
plotly | インタラクティブグラフ |
scikit-learn | 古典的機械学習 (回帰、分類、クラスタリング) |
TensorFlow / Keras | Google の深層学習 |
PyTorch | Meta の深層学習 (研究で主流) |
transformers | Hugging Face の LLM ライブラリ |
scipy | 科学計算 (最適化、信号処理、統計) |
statsmodels | 統計モデル (回帰分析、時系列) |
ファイル / 業務系
| ライブラリ | 用途 |
openpyxl | Excel (.xlsx) 読み書き |
xlsxwriter | Excel 書き出し (グラフ等) |
pandas.read_excel | Excel → DataFrame |
PyPDF2 / pypdf | PDF 読み書き |
reportlab | PDF 生成 |
python-docx | Word (.docx) |
Pillow (PIL) | 画像処理 |
OpenCV (cv2) | 本格画像処理 / コンピュータビジョン |
SQLAlchemy | ORM |
psycopg2 / asyncpg | PostgreSQL ドライバ |
PyMySQL | MySQL ドライバ |
redis | Redis クライアント |
boto3 | AWS SDK |
pip でのインストール
# 基本
pip install requests
# バージョン指定
pip install numpy==1.26.4
pip install "pandas>=2.0,<3.0"
# 複数まとめて
pip install -r requirements.txt
# 開発依存と本番依存
pip install -r requirements.txt # 本番
pip install -r requirements-dev.txt # 開発
# 一覧と凍結
pip list
pip freeze > requirements.txt
# アップグレード
pip install --upgrade requests
# アンインストール
pip uninstall requests
# venv (仮想環境) 推奨
python -m venv .venv
source .venv/bin/activate # Linux/Mac
.venv\Scripts\activate.bat # Windows
pip install -r requirements.txt
# Poetry (現代的な依存管理)
poetry init
poetry add requests
poetry add --dev pytest
poetry install
# uv (Rust 製の高速 pip 代替)
uv pip install requests
PyPI と仕様 (PEP)
- PyPI (Python Package Index):
https://pypi.org 公式パッケージリポジトリ。誰でも公開可能
- PEP (Python Enhancement Proposal): 言語仕様や標準ライブラリの拡張提案。
PEP 8 はコーディング規約、PEP 484 は型ヒント
- Python Standard Library Reference:
https://docs.python.org/3/library/ 公式ドキュメント
- awesome-python:
https://github.com/vinta/awesome-python 用途別の人気ライブラリリスト
サードパーティライブラリ利用例
# requests でシンプル HTTP
import requests
r = requests.get('https://api.github.com/users/python', timeout=10)
r.raise_for_status()
data = r.json()
# pandas で CSV 集計
import pandas as pd
df = pd.read_csv('sales.csv')
print(df.groupby('product')['amount'].sum())
# FastAPI で API サーバ
from fastapi import FastAPI
app = FastAPI()
@app.get('/users/{user_id}')
def get_user(user_id: int):
return {'id': user_id, 'name': 'taro'}
# openpyxl で Excel 操作
from openpyxl import load_workbook
wb = load_workbook('report.xlsx')
ws = wb['Sheet1']
ws['A1'] = '売上'
wb.save('report.xlsx')
ライブラリ選定のポイント
- メンテナンス: GitHub の最終コミットが 1 年以内か
- スター数 / ダウンロード数: PyPI Stats / pepy.tech で確認
- 型ヒント対応: 現代の Python では
py.typed が望ましい
- ライセンス: MIT / BSD / Apache が安全。GPL は配布制約がある
- 標準で足りる?: 軽量タスクは標準で十分。むやみに依存を増やさない
FAQ
Q: 標準ライブラリだけでどこまでできる?
A: 小規模 Web サーバ (http.server)、HTTP クライアント (urllib.request)、CSV / JSON / SQLite まで全部可能。本格用途で requests や pandas に置き換える形が定番。
Q: pip install が遅い / 失敗する
A: ネットワーク要因なら --index-url でミラー指定。ビルド失敗なら --only-binary=:all: で wheel のみに。最新は uv が圧倒的に速い。
Q: グローバルに pip install したくない
A: python -m venv .venv で仮想環境を作るのが標準。プロジェクトごとに分離できる。