すぐ忘れるPythonの話
環境周り
ryeでシュッと環境構築
vscodeの起動設定 (launch.json)
code: launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: main.py",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/src/hoge/__main__.py", // または ${file}
"console": "integratedTerminal",
"justMyCode": true,
"python": "${workspaceFolder}/.venv/bin/python",
"args": [
"--arg=hoge",
]
}
]
}
vscodeでのformatter設定 (settings.json)
もうruffだけ入れる感じでいいのでは
code: settings.json
{
"editor.defaultFormatter": "charliermarsh.ruff",
"editor.formatOnSave": true
}
}
mypy
mypyの Library stubs not installed for XXX エラーが出る
If mypy can’t find stubs for a third-party library, and it knows that stubs exist for the library, you will get a message like this:
サードパーティの型stub (型定義) が存在しているのをmypyが認識していて、まだインストールされていない場合に出力される
今回 openpyxl を使っていたらでて、types-openpyxlをryeでインストールしたら解消した
特定の行のmypyエラーを無視する
Generic型の実際の型を取得したい
一応 __orig_class__ と typing.get_args を使えばいけるが、これは文書化されていないし動作保証されてないので注意が必要
__orig_class__ の割当タイミングはオブジェクトの構築がほぼ終わるタイミング
そのため、 __init__ や __new__ の中でこの手段を使うことは基本できない
あくまで実装の詳細依存なので、将来Pythonのバージョンが上がったら動かなく可能性あり
logging
なにはともあれドキュメント
Pythonに限らないログ出力のガイドライン
ひとまずガツッと標準出力にログを出しちゃいたい
code: hoge.py
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger.errorの exc_info と stack_info