すぐ忘れるPythonの話
#シュッと出したい #Python
環境周り
ryeでシュッと環境構築
https://qiita.com/npkk/items/e10be19ea3e22debe1fd
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だけ入れる感じでいいのでは
https://qiita.com/npkk/items/e10be19ea3e22debe1fd#lintルールの設定
https://qiita.com/npkk/items/e10be19ea3e22debe1fd?utm_source=pocket_saves#vscodeの設定
code: settings.json
{
"python": {
"editor.defaultFormatter": "charliermarsh.ruff",
"editor.formatOnSave": true
}
}
mypy
mypyの Library stubs not installed for XXX エラーが出る
https://mypy.readthedocs.io/en/stable/running_mypy.html#library-stubs-not-installed
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が認識していて、まだインストールされていない場合に出力される
https://qiita.com/t2y/items/2a1310608da7b5c4860b#mypy-の簡単な紹介
今回 openpyxl を使っていたらでて、types-openpyxlをryeでインストールしたら解消した
特定の行のmypyエラーを無視する
https://stackoverflow.com/a/49220098
Generic型の実際の型を取得したい
https://stackoverflow.com/a/60984681
一応 __orig_class__ と typing.get_args を使えばいけるが、これは文書化されていないし動作保証されてないので注意が必要
https://docs.python.org/3/library/typing.html#typing.get_args
__orig_class__ の割当タイミングはオブジェクトの構築がほぼ終わるタイミング
そのため、 __init__ や __new__ の中でこの手段を使うことは基本できない
あくまで実装の詳細依存なので、将来Pythonのバージョンが上がったら動かなく可能性あり
logging
なにはともあれドキュメント
https://docs.python.org/ja/3/library/logging.html
https://docs.python.org/ja/3/howto/logging.html
Pythonに限らないログ出力のガイドライン
https://jisou-programmer.beproud.jp/ロギング/index.html
ひとまずガツッと標準出力にログを出しちゃいたい
code: hoge.py
logging.basicConfig(
level=logging.DEBUG,
handlers=logging.StreamHandler(sys.stdout),
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger.errorの exc_info と stack_info
https://docs.python.org/ja/3/library/logging.html#logging.Logger.debug