Today, while writing an AWS Lambda function, I needed to read a setting from an environment variable and convert it from a string to a boolean so I could use it in a condition. The obvious guesses are that Python will convert it automatically, or that bool("True") will do the job. But first of all, Python does not do automatic type conversion. This is important! It simply raises an error without any fuss. But surely you’d expect bool() to solve it, right?! In fact, this landmine cost me half an hour today…

In Python, no matter what you pass to bool(), it returns True. The only exception is bool(0), which returns False. The following cases also return True:

bool("True")
bool("false")
bool("False")
bool("0")

Yes, really. No matter what you pass in, you will almost always get True. If you accidentally put this into a condition, you will get strange behavior.

If you want to convert a string to a boolean, I recommend strtobool from distutils.util. It is a built-in Python module and quite powerful. See the examples below:

from distutils.util import strtobool

strtobool("True")
strtobool("Yes")
strtobool("Y")
strtobool("true")

All of these convert to True correctly. It’s a real lifesaver!!!