■ はじめに
Python の bool に関するメモ。
目次
【0】前提知識:Pythonの bool の正体 【1】Python の bool を扱う際の注意事項 【2】文字列 => bool に変換 1)補足:distutilsパッケージ
【0】前提知識:Pythonの bool の正体
https://note.nkmk.me/python-bool-true-false-usage/#booltruefalse1-0
より抜粋 〜〜〜〜 True, Falseはそれぞれ1, 0と等価。 〜〜〜〜
https://docs.python.org/ja/3/c-api/bool.html
Python の Bool 型は整数のサブクラスとして実装されています。
【1】Python の bool を扱う際の注意事項
* 以下の関連記事を参照のこと
Python の bool を扱う際の注意事項
https://dk521123.hatenablog.com/entry/2025/02/04/183714
【2】文字列 => bool に変換
# 簡易版 import os # <受ける変数> = "<対象文字列>".lower() == "true" # => 小文字にしてから、"true"と比較するだけ is_dry_run = os.getenv("DRY_RUN", "false").lower() == "true"
1)補足:distutilsパッケージ
* python 標準パッケージ * 公式API仕様には以下の記載されているので、 非推奨になりそうな予感 => 追記(2024/05/23):案の定、Python3.12 で廃止になった
https://docs.python.org/ja/3.10/distutils/index.html
より抜粋 ~~~~~~ 注釈 distutils パッケージ全体の使用は非推奨 (deprecated) であり、 Python 3.12 で削除されます。 この文書は参照のために維持されており、パッケージとともに削除されます。 ~~~~~~
https://docs.python.org/ja/3/distutils/apiref.html#distutils.util.strtobool
より抜粋
distutils.util.strtobool(val)
真偽値をあらわす文字列を真(1)または偽(0)に変換します。 真の値は y, yes, t, true, on そして 1 です。 偽の値は n, no, f, false, off そして 0 です。 val が上のどれでもない時は ValueError を起こします。
サンプル
from distutils.util import strtobool # ex1. False xxx = "False" is_xxx = strtobool(xxx) == 1 # is_xxx = False print(f"is_xxx = {is_xxx}") # ex2. True xxx = "True" is_xxx = strtobool(xxx) == 1 # is_xxx = True print(f"is_xxx = {is_xxx}")
参考文献
https://note.nkmk.me/python-bool-true-false-usage/
関連記事
Python ~ 基本編 / 文字列 ~
https://dk521123.hatenablog.com/entry/2019/10/12/075251
Python ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2014/08/07/231242
Python の bool を扱う際の注意事項
https://dk521123.hatenablog.com/entry/2025/02/04/183714