Last active
July 28, 2021 16:04
-
-
Save sempervent/65238a0f742d74dc351735a39d719c37 to your computer and use it in GitHub Desktop.
Check OS and Python Environment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
"""Check environments for an environmental variable value.""" | |
import os | |
def check_environment(env_var, default=None): | |
"""Check environments for an environmental variable.""" | |
def boolify(var): | |
if isinstance(default, bool): | |
if var in [0, '0', 'FALSE', 'False', 'false', 'F', 'f']: | |
return False | |
if var in [1, '1', 'TRUE', 'True', 'true', 'T', 't']: | |
return True | |
raise TypeError(f'Unable to evaluate expected boolean: {env_var}') | |
if env_var in os.environ: | |
return_var = os.environ[env_var] | |
elif env_var in globals(): | |
return_var = globals()[env_var] | |
elif env_var in locals(): | |
return_var = locals()[env_var] | |
else: | |
return default | |
if isinstance(default, bool) and not isinstance(return_var, bool): | |
return boolify(return_var) | |
if isinstance(default, int) and not isinstance(return_var, int): | |
return int(return_var) | |
if isinstance(default, float) and not isinstance(return_var, float): | |
return float(return_var) | |
return return_var |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
common usage is to have it as a seperate file, e.g.
check_environment.py
and then to usefrom check_environment import check_environment as ce
to use a shorthand notion within other files.