Last active
April 8, 2025 20:44
-
-
Save joewright/7c979efb5a434fbb59cfacbe9441f5bd to your computer and use it in GitHub Desktop.
environment pattern
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
import os | |
class EnvironmentConfiguration(): | |
def __init__(cls): | |
cls.name = os.environ.get('ENV_NAME', 'development') | |
cls.required_variable = os.environ.get('REQUIRED_VARIABLE') | |
cls.some_integer = int(os.environ.get('COOLNESS_LEVEL')) | |
cls.some_array = str(os.environ.get('GREAT_IDEAS')).split(',') | |
if not cls.required_variable: | |
raise Exception('REQUIRED_VARIABLE is not set in the environment variables.') | |
ENV = EnvironmentConfiguration() |
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
from .environment import ENV | |
# my editor has cool type hints and autocomplete with this useful typed object | |
if ENV.name == 'something': | |
print('incredible') |
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
# don't do this | |
import os | |
# no editor autocomplete, I'm clicking back and forth, copying strings all over the place, bound to cause a typo | |
if os.environ.get('REQUIRED_VARIABLE') == '1': | |
print('great') | |
if os.environ.get('COOLNESS_LEVEL'): | |
# check the types | |
value = os.environ.get('COOLNESS_LEVEL') | |
if isinstance(value, str): | |
value = value.split(',') | |
# now we can finally use the value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment