Python

How to Configure Your Project with Pydantic BaseSettings

Configuring the projects by utilizing Pydantic’s BaseSettings is an essential approach to configuration handling in Python applications. Pydantic, a versatile library, offers a precise data validation and efficient management of settings, applying Python’s type translations. By creating a dedicated configuration class that inherits from BaseSettings, the developers can effortlessly organize, validate, and access the project-specific parameters. Utilizing the basic capability of BaseSettings to map the environment variables, the configuration process becomes more built-in, enabling the overrides and automatic validation.

Method 1: Pydantic’s BaseSettings Configuration for Web Application

Configuring projects effectively is a critical part of software development, and Pydantic’s BaseSettings offers the best method to assemble the configuration handling in Python applications. By combining the data validation and settings management through Python type translations, Pydantic simplifies the process while ensuring the reliability of our project’s configuration. In this step-by-step guide, we’ll walk through the process of configuring our project using Pydantic’s BaseSettings.

To start, install Pydantic. The first step is to install the Pydantic library if it’s not already part of our project’s dependencies.  We can achieve this using the following command in our terminal:

!pip install pydantic-settings
from pydantic_settings import BaseSettings

 

To create and for the configuration of the class, Pydantic excels at defining the configuration settings through a dedicated class that inherits from the BaseSettings. Start by importing the necessary module and creating a configuration class. In this example, we’ll create an “AppConfig” class for an application.

For this instance, we define three configuration settings, e.g. app_name, debug, and log_level. These default values are assigned to ensure that our application runs smoothly, even if it is not explicitly provided during configuration.

For the environment variables mapping, Pydantic simplifies the connection between the environment variables and the configuration settings. It automatically maps the environment variables to the attributes in our configuration class. For instance, the attribute app_name is connected to the APP_NAME environment variable.

class AppConfig(BaseSettings):
    app_name: str = "MyApp"
    debug: bool = False
    log_level: str = "info"

 

This linking of attributes and environment variables is based on naming conventions. Pydantic converts the attribute names to uppercase and replaces the underscores with double underscores to generate the corresponding environment variable name.

To access the configuration settings with the configuration class, accessing the settings becomes effortless. Create an instance of the “AppConfig” class, and we can interact with the settings just like the regular class attributes:

config = AppConfig()
print(config.app_name)
print(config.debug)
print(config.log_level)

 

This approach combines the configuration management into our project, increasing its organization and maintainability.

By following these steps, we set the foundation for strong configuration management using Pydantic’s BaseSettings. We utilize Pydantic’s capability to handle the data validation, type conversion, and environment variable mapping in this process. This simplifies our project’s configuration and helps prevent errors that are caused by incorrect or mismatched settings.

!pip install pydantic-settings
from pydantic_settings import BaseSettings
class AppConfig(BaseSettings):
    app_name: str = "MyApp"
    debug: bool = False
    log_level: str = "info"

config = AppConfig()
print(config.app_name)
print(config.debug)
print(config.log_level)

 

In summary, Pydantic’s BaseSettings offers a solution for configuring our projects. By adopting this approach, we establish a structured framework for managing the configuration settings while ensuring the data validation and type conversion. With its easy-to-use environment variable mapping and built-in settings access, Pydantic allows us to build fast and adaptable applications. So, consider utilizing Pydantic’s BaseSettings to enhance our project’s configuration management and set the rules for efficient development.

Method 2: Automatic Validation and Type Conversion

Consider a scenario where we develop a weather forecasting application. We want to ensure that the configuration settings for temperature limits are properly validated and converted to the correct data types.

In this example, we define a “WeatherConfig” class using Pydantic’s BaseSettings. Inside the class, we have two configuration settings, min_temperature and max_temperature, both initialized with default values. These settings represent the minimum and maximum temperatures that our application will use for weather predictions.

!pip install pydantic-settings
from pydantic_settings import BaseSettings
class WeatherConfig(BaseSettings):
    min_temperature: float = -12.0
    max_temperature: float = 50.0

config = WeatherConfig()

print("Minimum Temperature:", config.min_temperature)
print("Maximum Temperature:", config.max_temperature)

 

When we create an instance of the “WeatherConfig” class, Pydantic automatically performs the validation and type conversion. Here’s how it will happen:

For the validation, Pydantic checks if the provided default values (-12.0 and 50.0) are of the correct type (float). If not, it raises a validation error, ensuring that the configured values stick to the specified type.

We provide the environment variables with new temperature values for type conversion, like MIN_TEMPERATURE=-10 and MAX_TEMPERATURE=45. Pydantic automatically converts these values to floats (-10 and 45.0) since the settings are defined with the float type.

Here, we rely on Pydantic’s automatic validation and type conversion to ensure that our application’s configuration remains consistent and accurate. If a developer accidentally provides a non-numeric value for these temperature settings or uses an invalid data type, Pydantic catches the error during initialization, thus preventing issues.

Pydantic’s BaseSettings not only simplifies the configuration management but also adds an extra layer of safety to its built-in validation and type conversion mechanisms. This ensures that our application’s settings are both accurate and appropriately formatted, contributing to a more reliable and strong software solution.

Method 3: Configuration Overrides

Consider an example where we want to build a content management system (CMS) with a feature to turn the user registration on or off. We want to provide the flexibility to override this configuration using the environment variables for different deployment environments.

In this scenario, the “CMSConfig” class is defined with a single configuration setting or required field, e.g. allow_registration, which is initialized to “False” by default. This setting controls whether the user registration is allowed in the CMS.

!pip install pydantic-settings

from pydantic_settings import BaseSettings

class CMSConfig(BaseSettings):
    allow_registration: bool = False

config = CMSConfig()

print("User Registration Allowed:", config.allow_registration)

 

To display the configuration overrides, let’s say we deploy our CMS in a testing environment and we want to enable the user registration for testing purposes. We can achieve this by setting the ALLOW_REGISTRATION environment variable:

allow_registration: bool = True

 

When we create an instance of the “CMSConfig” class, Pydantic automatically maps the ALLOW_REGISTRATION environment variable to the allow_registration attribute. This results in overriding the default value, enabling the user registration during testing.

By employing the configuration overrides, we gain the flexibility to adapt our application’s behavior to different environments without modifying our code. This simplifies the configuration management and allows us to make quick adjustments based on deployment needs.

Conclusion

The utilization of Pydantic’s BaseSettings for configuring the projects proves the library’s ability to manage the settings with precision. Through the effortless combination of data validation, automatic type conversion, and environment variable mapping, Pydantic increases the configuration management. Whether in a weather app or a basic configuration like AppConfig, Pydantic combines the process and enhances software reliability.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.