【Python】Python ~ 基本編 / bool ~

■ はじめに

 文字列からbool に変換する際に
【1】の「意図した動作にならなかった例」のように
実装したが、うまくいかなかったので、メモっておく。

目次

【1】文字列 => bool に変換する際の注意点
【2】文字列 => bool に変換
 1)サンプル
 2)補足:distutilsパッケージ

【1】文字列 => bool に変換する際の注意点

* bool("<String>")でも boolへの変換は可能だが
 以下の「意図した動作にならなかった例」のように
 bool('False') は Trueになってしまう。

 => bool() の仕様として、以下のようになるため。
 + True : 空でない文字列str型すべて
 + False : 空文字列

意図した動作にならなかった例

xxx = "False"
is_xxx = bool(xxx)

# is_xxx = True (!!!???)
print(f"is_xxx = {is_xxx}")

【2】文字列 => bool に変換

* distutils.util.strtoboolを使用する
 => 「補足:distutilsパッケージ」も参照。

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 を起こします。

1)サンプル

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}")

2)補足:distutilsパッケージ

* python 標準パッケージ
* 公式API仕様には以下の記載されているので、
 非推奨になりそうな予感

https://docs.python.org/ja/3/library/distutils.html

より抜粋(分かりづらい日本語なので英語も付けておく)
~~~~~
Python ユーザの大半は
このパッケージを直接使いたくはないでしょうが、
代わりに Python Packaging Authority が保守している
クロスバージョンツールを使うでしょう。
Most Python users will not want to use this module directly,
 but instead use the cross-version tools maintained
 by the Python Packaging Authority.

特に、setuptools は distutils の改良された代替品で、
以下を提供しています:
In particular, setuptools is an enhanced alternative
 to distutils that provides:
~~~~~
=> ただ「setuptools」は標準ではなさそう、、、

参考文献

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