はじめに
Pythonでの作成物における設定ファイルとして、
TOMLを多用するため自分の中での整理も兼ねてまとめました。
TOMLファイルの読み込み
TOMLを読み込むためのパーサーについては、
Pythonのバージョンによって推奨されるものが異なっている。
それぞれについての利用法を、以下の項目にて記載します。
Python 3.11 〜
Python 3.11以降のバージョンでは、
標準ライブラリに追加された「tomllib」が利用できます。
import tomllib
from typing import Any
# strではなく、Pathオブジェクトを渡してもOK
toml_file_path: str = "project_dir/config/settings.toml"
# tomllibは"rb"でひらく
with open(toml_file_path, mode="rb") as toml_file:
toml_data: dict[str, Any] = tomllib.load(toml_file)
〜 Python 3.10
Python 3.10までのバージョンでは、
外部ライブラリである「toml」のインストールが必要です。
pip install toml
import toml
from typing import Any
# strではなく、Pathオブジェクトを渡してもOK
toml_file_path: str = "project_dir/config/settings.toml"
# tomlは"r"でファイルをひらく
with open(toml_file_path, mode="r", encofing="utf-8") as toml_file:
toml_data: dict[str, Any] = toml.load(toml_file_path)
TOMLへ値を埋め込む
TOMLに記載した文字列の中に、Pythonから値を渡して
その値が入った文字列として展開することも可能です。
下記はそのサンプルコードとなりますが
TOMLから値を読み取る際に、"{msg}"に対してPythonコード内で値を渡しています。
settings.toml
[introduce]
[introduce.language]
content ="""
私の好きなプログラミング言語を紹介します。
{msg}
"""
read_toml.py
import tomllib
from typing import Any
toml_file_path: str = "project_dir/config/settings.toml"
with open(toml_file_path, mode="rb") as toml_file:
toml_data: dict[str, Any] = tomllib.load(toml_file)
# ブラケット記法でTOMLから値を取得する際に、任意の文字列を埋め込む
MESSAGE = toml_data["introduce"]["language"]["content"].format(
msg="好きな言語はPythonです。"
)
print(MESSAGE)
# 私の好きなプログラミング言語を紹介します。
# 好きな言語はPythonです。
TOMLに対してTOMLの値を埋め込む
上記の応用とも言えますが、PythonからTOMLに渡す値は
その値自身もTOMLから取得したものを利用することが可能です。
ベースとなる文章を作り、その中にカスタム文章を入れるといった場合に役立つ
大枠となる親の定型文があり、その中に数パターンある子供の定型文を
状況によって切り替えて使いたいといった場合に役立ちます。
下記はそのサンプルコードとなりますが、
ネストしているのが見て取れるかと思います。
settings.toml
[introduce]
[introduce.language]
content ="""
私の好きなプログラミング言語を紹介します。
{msg}
"""
[introduce.framework]
content = """
よく書くのは{lang}であり、
好みのフレームワークは
{fw}です。
"""
read_toml.py
import tomllib
from typing import Any
toml_file_path: str = "project_dir/config/settings.toml"
with open(toml_file_path, mode="rb") as toml_file:
toml_data: dict[str, Any] = tomllib.load(toml_file)
# 任意の文字列を埋め込むところに、TOMLから取得した文字列を埋め込む
MESSAGE = toml_data["introduce"]["language"]["content"].format(
msg=toml_data["introduce"]["framework"]["content"].format(
lang="Python", fw="Flask"
)
)
print(MESSAGE)
# 私の好きなプログラミング言語を紹介します。
# よく書くのはPythonであり、
# 好みのフレームワークは
# Flaskです。
参考
- TOML公式
- tomllib --- TOML ファイルの解析
- toml Library
- TOML っていいな