
Have you ever needed to generate specific types of test data that Mimesis doesn’t provide out of the box? While Mimesis offers an extensive collection of built-in providers, real-world applications often require custom data that reflects your unique business domain. In this article, we’ll explore how to extend Mimesis’s capabilities by creating your own custom providers.
Rather than diving into complex patterns or advanced features, we’ll walk through a practical, hands-on example of building a simple product data generator. By the end of this guide, you’ll understand how to create custom providers that integrate seamlessly with Mimesis’s existing functionality.
Creating Your First Custom Provider
Let’s start by creating a custom provider for generating product-related data. The goal is to create a provider that can generate categories and conditions for an e-commerce application. Here’s how we can implement this:
from mimesis.providers import BaseProvider
class ProductProvider(BaseProvider):
"""Provider for generating product-related data."""
def product_category(self) -> str:
categories = ['Electronics', 'Books', 'Clothing', 'Home', 'Sports']
return self.random.choice(categories)
def product_condition(self) -> str:
conditions = ['New', 'Like New', 'Used', 'Refurbished']
return self.random.choice(conditions)
Let’s examine the key components of this custom provider:
- Inheritance from BaseProvider: By inheriting from BaseProvider, our custom class gains access to Mimesis’s built-in random number generation capabilities through self.random. This ensures our custom provider maintains consistency with Mimesis’s seeding system.
- Method Definition: Each method in our provider generates a specific type of data. Here, product_category() and product_condition() each return a random choice from a predefined list of values.
- Type Hints: The -> str annotations indicate that both methods return string values, making the code more maintainable and easier to understand.
This simple provider serves as a foundation that we can build upon to generate more complex product data. In the next section, we’ll see how to use this custom provider alongside Mimesis’s built-in functionality to create complete product records.
Using Your Custom Provider
Now that we have our custom provider, let’s put it to work alongside Mimesis’s built-in Field class to generate complete product records. We’ll combine our custom category and condition generators with Mimesis’s numeric capabilities to create realistic product data:
from mimesis import Field
from mimesis.enums import Locale
# Set seed for reproducibility
seed = 42
field = Field(locale=Locale.EN, seed=seed)
custom = ProductProvider(seed=seed)
# Generate a product
product = {
'category': custom.product_category(),
'condition': custom.product_condition(),
'price': round(field('numeric.float_number', start=10, end=1000), 2)
}
print("Single Product Example:")
for key, value in product.items():
print(f"{key}: {value}")
Single Product Example: category: Electronics condition: New price: 643.03
This code demonstrates several important concepts about working with custom providers:
- Seeding for Reproducibility: By setting the same seed value for both our custom provider and the Field instance, we ensure that our data generation is reproducible – running this code multiple times will produce the same output.
- Combining Providers: We seamlessly mix methods from our custom provider (custom.product_category() and custom.product_condition()) with Mimesis’s built-in Field class (field(‘numeric.float_number’)).
- Price Formatting: The round() function ensures our prices have exactly two decimal places, making them look like realistic currency values.
In the output, we can see how our custom provider generates sensible product data: an Electronics item in New condition priced at $643.03. This demonstrates how easily custom providers can work alongside Mimesis’s built-in functionality to create domain-specific test data.
Scaling Up: Using the Schema API
While generating individual products is useful, real-world testing often requires larger datasets. Let’s explore how to combine our custom provider with Mimesis’s Schema API to generate multiple product records efficiently:
from mimesis import Schema
# Set seed for reproducibility
seed = 42
field = Field(locale=Locale.EN, seed=seed)
custom = ProductProvider(seed=seed)
def product_schema():
return {
'id': field('numeric.integer_number', start=1000, end=9999),
'category': custom.product_category(),
'condition': custom.product_condition(),
'price': round(field('numeric.float_number', start=10, end=1000), 2),
'created_at': field('datetime.datetime')
}
# Generate multiple products
schema = Schema(schema=product_schema, iterations=3)
products = schema.create()
print("\nMultiple Products from Schema:")
for i, product in enumerate(products, 1):
print(f"\nProduct {i}:")
for key, value in product.items():
print(f"{key}: {value}")
Multiple Products from Schema: Product 1: id: 2824 category: Electronics condition: New price: 34.76 created_at: 2025-01-24 08:15:14.146316 Product 2: id: 5506 category: Clothing condition: Like New price: 252.44 created_at: 2025-11-24 17:05:37.442417 Product 3: id: 3286 category: Books condition: Like New price: 739.11 created_at: 2025-01-03 06:14:32.631262
The Schema API provides a powerful way to generate multiple records following a consistent structure. Let’s examine what makes this approach particularly effective:
- Schema Definition: The product_schema() function defines our data structure, combining both custom and built-in providers. It adds important fields like unique IDs and timestamps that weren’t present in our single-product example.
- Multiple Record Generation: By setting iterations=3 in the Schema constructor, we generate multiple products with a single line of code. This can easily be scaled to thousands of records if needed.
- Data Variety: Looking at the output, we can see how our generator creates diverse product records – different categories, conditions, and prices, all while maintaining realistic values within our specified ranges.
The resulting dataset shows how our custom provider integrates naturally with Mimesis’s Schema API to create a rich, varied collection of product records. Each record includes all necessary fields with appropriate data types and ranges, making it suitable for testing database operations, API endpoints, or user interface components.
Taking Your Custom Providers Further
Throughout this article, we’ve explored how to create, use, and scale custom providers in Mimesis. Starting from a simple product data generator, we progressed to generating multiple records with the Schema API, demonstrating how custom providers can seamlessly integrate with Mimesis’s built-in functionality.
The approach we’ve outlined can be adapted to generate any kind of domain-specific data your application needs. Whether you’re building an inventory system, a content management platform, or any other specialized application, custom providers offer a clean, maintainable way to generate realistic test data.
Some ways you might extend this pattern include:
- Additional Fields: Expand the provider with methods for generating product descriptions, SKUs, or manufacturer information
- Related Data: Create providers for related entities like vendors, warehouse locations, or shipping information
- Data Validation: Add constraints to ensure generated data meets your business rules
By understanding how to create custom providers, you’ve added a powerful tool to your testing toolkit. You can now generate exactly the kind of data your application needs while maintaining all the benefits of Mimesis’s robust infrastructure.
