0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

パラメータをconfig.pyに書いてる

0
Last updated at Posted at 2025-12-12

パラメータをconfig.yamlではなくconfig.pyに書く理由

pythonでコードを書くとき
いつもconfig.yamlを作成して、そこにパラメータを記載している。
そしてmain.pyから読み込んで使用する。

config.yaml
hoge:
  fuga: piyo
main.py
from pathlib import Path

import yaml


def load_config(path: str) -> dict:
    with Path(path).open("r") as f:
        d = yaml.safe_load(f)
    return d


def main() -> None:
    cfg = load_config("config.yaml")
    print(cfg)


if __name__ == "__main__":
    main()

しかし、面倒に思うことがあった。

パラメータを変更した直後、F5を押してしまう

プログラムの動きをちょっと確認したい時に、パラメータを変えて実行することがある。
パラメータを変更した直後、手癖でF5(デバッグの開始)を押すと

  File "~~~~~~~~~~~~~~\config.yaml", line 1
    hoge:
         ^
SyntaxError: invalid syntax

・・・となり、もちろんエラーとなる。
なので一度main.pyに移動してからF5を押し直すことになり、ダルい。

他にも面倒なことがある。

yaml読み込み関数を作成しなければならない

main.py
def load_config(path: str) -> dict:
    with Path(path).open("r") as f:
        d = yaml.safe_load(f)
    return d

地味にこれがダルい。


最初からconfig.pyに書けば良くない?

パラメータなんてものは結局dictで表現できるので、最初からそれでいいじゃん。
ということで以下のようにした。

config.py
def load_config() -> dict:
    cfg = {
        "hoge": {
            "fuga": "piyo",
        },
    }
    return cfg


if __name__ == "__main__":
    import main

    main.main()
main.py
import config


def main() -> None:
    cfg = config.load_config()
    print(cfg)


if __name__ == "__main__":
    main()

これならconfig.py上でパラメータを変更してそのままF5で実行できる。
気持ちいい。

(これって当たり前?)

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?