Using a Python dictionary as a switch statement


Python tip:

You can use a dictionary to implement switch-like behavior.

For example:

class ProductionConfig:
    ELASTICSEARCH_URL = "https://elasticsearch.example.com"


class DevelopmentConfig:
    ELASTICSEARCH_URL = "https://development-elasticsearch.example.com"


class TestConfig:
    ELASTICSEARCH_URL = "http://test-in-docker:9200"


CONFIGS = {
    "production": ProductionConfig,
    "development": DevelopmentConfig,
    "test": TestConfig,
}


def load_config(environment):
    return CONFIGS.get(environment, ProductionConfig)


print(load_config("production"))
# <class '__main__.ProductionConfig'>
print(load_config("test"))
# <class '__main__.TestConfig'>
print(load_config("unknown"))
# <class '__main__.ProductionConfig'>