Create a gist now

Instantly share code, notes, and snippets.

@datagrok /
Last active Feb 27, 2017

What would you like to do?
envbool: a function to obtain a boolean value from an environment variable
def envbool(key, default=False, unknown=True):
"""Return a boolean value based on that of an environment variable.
Environment variables have no native boolean type. They are always strings, and may be empty or
unset (which differs from empty.) Furthermore, notions of what is "truthy" in shell script
differ from that of python.
This function converts environment variables to python boolean True or False in
case-insensitive, expected ways to avoid pitfalls:
"Yes", "Y", "True", "T", and "1", case insensitive, become True
"False", "F", "No", "N", and "0", case insensitive, become False
unset or empty becomes False by default (toggle with 'default' parameter.)
any other value becomes True by default (toggle with 'unknown' parameter.)
return {
'yes': True, 'y': True, 'true': True, '1': True, 't': True,
'no': False, 'n': False, 'false': False, '0': False, 'f': False,
'': default,
}.get(os.getenv(key, '').lower(), unknown)
# Read a boolean setting from an environment variable (always a string) and
# deal correctly with unset, null, and unknown values.
def envbool (key, default: false, unknown: true)
%w(yes y true t 1).map {|k|[k,true]} +
%w(no n false f 0).map {|k|[k,false]} +
[['', default]]
].fetch(ENV.fetch(key, '').downcase, unknown)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment