Python

How to Manage Multiple Data Types with Pydantic Union

Managing different types of data is important in programming. Pydantic’s Union feature helps with this. Pydantic is a tool in Python that lets us create the organized data models using the type hints. With Union, we can make the fields that accept many types of data. This makes things flexible while also keeping the data safe. Pydantic checks and organizes the input data based on the types we set. So, it’s easy to work with various data types in one system. This makes programming more robust and more adaptable, all because of Pydantic.

Example 1:

Effectively managing a wide range of data types is a challenging task in this era of programming. The Pydantic library, Python’s most powerful tool, offers the strongest toolkit to address this issue, i.e. the Union. This feature is a versatile solution that empowers the developers to efficiently use the complex, diverse data types within a single system.

Think of it as we are developing a messaging application that needs to handle the messages of varying natures that range from a simple text to complex multimedia files using the Pydantic’s Union which is a feature that is truly powerful. By applying the Union, we can create an adaptable data model:

!pip install pydantic

!pip install --upgrade pydantic

from pydantic import BaseModel

from typing import Union, Dict

class Message(BaseModel):

  content: Union[str, bytes]

The beauty of this lies in the fact that the content field can effortlessly accommodate both text and binary data. This flexibility arises the need for maintaining the separate structures to handle the distinct data types.

Consider another scenario where a financial application deals with transactions involving numerical amounts or textual explanations. Once again, Pydantic’s Union will help us:

class Transaction(BaseModel):

  amount: Union[float, str]

This “Transaction” class handles both the numerical values and string representations of amounts. The result makes the entire data management process very smooth.

To know, Pydantic’s Union isn’t just about versatility; it also decently addresses the scenarios involving the optional fields. Look into an example of a user profile where the user’s age could either be represented by an integer or by absent:

class UserProfile(BaseModel):

  name: str

  age: Union[int, None]

This model’s age field has the integer values and scenarios where the users haven’t shared their ages. This real-world application reveals the power of the solution.

To go beyond the basics in Pydantic to explore the advanced options, Pydantic’s Union can be used in complex use cases. Again, for an e-commerce setup where a product’s price could be displayed in multiple ways such as a regular price or a discounted rate:

class Product(BaseModel):

  name: str

  price: Union[float, Dict[str, float]]

The “price” field can have either a direct numerical value or a dictionary that provides a detailed pricing information. This adaptability level increases Pydantic’s Union’s utility in tackling complex data scenarios.

Full code:

!pip install pydantic
!pip install --upgrade pydantic
from pydantic import BaseModel
from typing import Union, Dict
class Message(BaseModel):
    content: Union[str, bytes]

class Transaction(BaseModel):
    amount: Union[float, str]

class UserProfile(BaseModel):
    name: str
    age: Union[int, None]

class Product(BaseModel):
    name: str
    price: Union[float, Dict[str, float]]
# Creating instances of the models
message = Message(content="Hello, world!")
transaction = Transaction(amount=100.50)
user_profile = UserProfile(name="Alice", age=30)
product = Product(name="Widget", price=12.99)

# Accessing and printing the attributes
print(message.content)
print(transaction.amount)
print(user_profile.name, user_profile.age)
print(product.name, product.price)

In short, from the previously-explained example, we can figure out that the Pydantic Union is a transformational tool in the programmer’s toolkit; it revolutionizes how the diverse data types are managed within the Python applications. Whether we are designing the messaging platforms, financial systems, user profiles, or e-commerce websites, Pydantic’s Union allows us to effortlessly navigate the complex data scenarios with precision.

Example 2:

In this vast era of software development, effectively managing the various data types is a task that demands fine work. Pydantic, a Python library, presents a versatile solution which is known as Union that simplifies this complex process. This unique feature empowers the developers to go through the complexities of diverse data types within a single framework while ensuring the data validation.

For instance, we have a situation where we construct a healthcare application. This application needs to handle the patient records containing a mix of data types such as integers for age, strings for names, and even Boolean values for medical conditions. Using Pydantic’s Union, we can create an adaptable data model:

!pip install pydantic
from pydantic import BaseModel
from typing import Union, Dict
class PatientRecord(BaseModel):
    name: str
    age: Union[int, str]
    has_medical_condition: bool

Here, the “age” field has the numerical and textual data, while the has_medical_condition field has the data type Boolean values. This smooth combination of different data types enhances the application’s flexibility.

In another scenario, for an inventory management system for a retail business, this system needs to handle the product information, including prices, which can be numeric values or string representations of prices. The Pydantic Union proves invaluable in this context:

class ProductInfo(BaseModel):

  product_name: str

  price: Union[float, str]

This ProductInfo mode manages the conventional numeric and text-based price descriptions, offering a unified approach for diverse data types.

Moreover, Pydantic’s Union is not only about combining the various data types but also addressing the optional data. Imagine that we are working on a user profile setup where some users might not share their contact numbers. Pydantic’s Union facilitates this gracefully:

class UserProfile(BaseModel):

  username: str

  contact_number: Union[str, None]

In this example, the contact_number field can handle the string values and account for situations where the users choose not to provide their contact information.

Furthermore, Pydantic’s Union is a powerful tool when handling more intricate data representations. We can also utilize it in other applications. For example, in a weather forecasting application, we may need to manage the temperature data that could be either in Celsius or Fahrenheit. With Pydantic’s Union, we can ensure a coherent data model:

class WeatherData(BaseModel):

  location: str

  temperature: Union[float, Dict[str, float]]

Here, the “temperature” field can include both a single numerical value and a dictionary that provides a detailed temperature breakdown. This dynamic approach to data representation gives precision in our application.

!pip install pydantic
from pydantic import BaseModel
from typing import Union, Dict
class PatientRecord(BaseModel):
    name: str
    age: Union[int, str]
    has_medical_condition: bool

class ProductInfo(BaseModel):
    product_name: str
    price: Union[float, str]

class UserProfile(BaseModel):
    username: str
    contact_number: Union[str, None]

class WeatherData(BaseModel):
    location: str
    temperature: Union[float, Dict[str, float]]

# Creating instances of the models
patient = PatientRecord(name="John Doe", age=25, has_medical_condition=True)
product = ProductInfo(product_name="Widget", price=12.99)
user_profile = UserProfile(username="alice123", contact_number="123-456-7890")
weather = WeatherData(location="Cityville", temperature=25.5)

# Printing the instances
print("Patient Record:")
print(patient)

print("\nProduct Info:")
print(product)

print("\nUser Profile:")
print(user_profile)

print("\nWeather Data:")
print(weather)

The observation from the discussed examples unveils that Pydantic’s Union emerges as an essential tool for developers, enabling them to handle the complex and diverse data types within Python applications. Its capacity to handle multiple data types within a single field combines the data management, increases the code clarity, and preserves the data integrity. Whether we are shaping the healthcare systems, retail solutions, user profiles, or data applications, Pydantic’s Union empowers us to manage the multi-data type scenarios with proficiency.

Conclusion

Pydantic’s Union is a crucial tool for handling the different data types together in the programming world. It helps the developers to create flexible data models that deal with many data types while keeping things organized and correct. From healthcare apps to managing the products, Pydantic’s Union can smoothly put together the different types of information. It’s also good at managing the data that might not always be there and the more complex data setups. In simple terms, Pydantic’s Union is like a super tool for programmers.

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.