Skip to content

Conversation

@rodrigobnogueira
Copy link

Add Excluding declaration and Faker(unique=True) parameter

Related Issues

Closes #1132 - Ability to exclude previous values from next model generation
Closes #305 - Option to make Faker return unique values

Summary

This PR adds two related features for generating values while avoiding specific ones:

  1. Excluding declaration - A wrapper that excludes specific values from any base declaration
  2. Faker(unique=True) parameter - Leverages Faker's built-in uniqueness feature

Motivation

These features address common use cases:

  • Generating unique identifiers/codes that don't match existing data
  • Ensuring two fields in the same factory have different values (e.g., primary vs secondary language)
  • Excluding "banned" or "invalid" values from random selections

Changes

Excluding Declaration

from factory import Excluding, Faker
from factory.fuzzy import FuzzyChoice

# Exclude specific values
status = Excluding(
    FuzzyChoice(['active', 'inactive', 'banned']),
    exclude=['banned']
)

# Dynamic exclusion based on another field
class UserFactory(factory.Factory):
    primary_language = FuzzyChoice(['en', 'fr', 'de'])
    secondary_language = Excluding(
        FuzzyChoice(['en', 'fr', 'de']),
        exclude=SelfAttribute('primary_language')
    )

Features:

  • Works with any base declaration (FuzzyChoice, Faker, LazyAttribute, etc.)
  • Supports static lists, single values, or dynamic declarations for exclusion
  • Configurable max_retries (default: 50)
  • Recursive _make_hashable for nested structures
  • Plain value exclusion fails immediately (no wasted retries)

Faker(unique=True)

# Generate unique emails across factory calls
email = factory.Faker('email', unique=True)

This delegates to Faker's built-in .unique attribute.

Testing

  • 15 new tests covering both features
  • Full test suite: 459 passed
  • Covers: basic functionality, edge cases, exhaustion handling, dynamic exclusions, factory integration

Checklist

  • Tests pass locally
  • New tests added for new functionality
  • Docstrings added with examples
  • Follows existing code style

- Add Excluding declaration that wraps base declarations and excludes
  specified values with retry logic
- Add unique parameter to Faker for generating unique values
- Supports static exclusion lists and dynamic exclusions via SelfAttribute
- Implements recursive _make_hashable for nested structures
- Plain value exclusion raises immediately without retrying
- Comprehensive test coverage with 15 new tests
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Ability to exclude previous values from next model generation Option to make Faker return unique values

1 participant