Skip to content

Conversation

@rodrigobnogueira
Copy link

@rodrigobnogueira rodrigobnogueira commented Dec 27, 2025

Related Issues

Closes #1140 - Sentinel object for excluding items in DictFactory

Summary

This PR adds a MISSING sentinel value for DictFactory that allows excluding specific keys from the generated dictionary.

Motivation

When generating dictionary payloads (e.g., API responses), there are cases where you want to conditionally exclude certain keys:

  • Optional fields that should only appear under certain conditions
  • Fields that should be absent rather than null
  • Dynamic payloads where presence/absence of keys matters

Changes

MISSING Sentinel

Features:

  • Singleton sentinel with falsy boolean value
  • Works with Transformer declarations
  • Can be conditionally returned from LazyFunction
  • Overridable at call time to include the key
import factory

class ResponseFactory(factory.DictFactory):
    name = factory.Faker('name')
    email = factory.MISSING  # This key will be excluded

result = ResponseFactory()
# Result: {'name': 'John Doe'}
# Note: 'email' key is not present

# Conditional exclusion
class ConditionalFactory(factory.DictFactory):
    field = factory.LazyFunction(lambda: factory.MISSING if condition else "value")

# Override to include
result = ResponseFactory(email="user@example.com")
# Result: {'name': 'John Doe', 'email': 'user@example.com'}

Testing

  • 9 new tests covering the feature
  • Full test suite: 448 passed
  • Covers: basic functionality, override behavior, Transformer interaction, LazyFunction usage

Checklist

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

This adds a MISSING sentinel value that can be used with DictFactory
to exclude specific keys from the generated dictionary.

Example usage:
    class MyFactory(factory.DictFactory):
        name = factory.Faker('name')
        email = factory.MISSING  # This key will be excluded

The MISSING sentinel:
- Is a singleton with a falsy boolean value
- Can be used with Transformer declarations
- Can be conditionally returned from LazyFunction
- Can be overridden at call time to include the key
@chriswyatt
Copy link

I tested this in one of my projects and it seems to work fine

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.

Sentinel object for excluding items in DictFactory

2 participants