netherframe Deferred Binding Pattern
Overview
The Deferred Binding Pattern is a fundamental design principle in netherframe that provides a clean, intuitive way to construct infrastructure trees. It separates the configuration of constructs from their binding to the tree, enabling powerful composition patterns while maintaining Python's natural syntax.
Core Principles
1. __init__ is for Configuration ONLY
The __init__ method of any Construct subclass is solely for accepting construct-specific configuration (e.g., the cidr_block for a VPC). It must not accept nf_id or scope.
2. __call__ is for Binding ONLY
The __call__ method is solely for binding a not-yet-bound construct to its place in the construct tree. It is the only entry point for providing nf_id and scope.
3. All Constructs Start as Templates
Every call to MyStack() or Resource() creates a not-yet-bound template or factory instance.
4. Binding is an Explicit Step
The template instance is then explicitly bound by calling it: template_instance(nf_id="...", scope=...). This call returns the final, bound construct.
5. Parents Adopt and Bind Their Children
During a parent's binding process, it automatically finds and binds all deferred children that were attached to it during its __init__.
Implementation Example
Basic Usage
from nf.core import App, Stack, Resource
# Step 1: Create template constructs
app = App() # App template
stack = Stack() # Stack template
# Step 2: Bind them to the tree
app = app("my-app") # Now bound with ID "my-app"
stack = stack("my-stack", scope=app) # Now bound with ID "my-stack" under app
Custom Stack with Resources
class MyStack(Stack):
def __init__(self, vpc_cidr="10.0.0.0/16"):
# Parent __init__ creates a stack template
super().__init__()
# Configuration stored normally
self.vpc_cidr = vpc_cidr
# Resources created in context automatically register as deferred children
with self:
self.vpc = Resource(type="aws_vpc", cidr_block=vpc_cidr)
self.subnet = Resource(
type="aws_subnet",
vpc_id=self.vpc.output.id, # Lazy references work!
cidr_block="10.0.1.0/24",
)
# Usage is clean and intuitive
app = App()("my-app")
stack = MyStack(vpc_cidr="10.1.0.0/16")("my-stack", scope=app)
# After binding, all resources are bound with their attribute names as IDs
print(stack.vpc.nf_id) # "vpc"
print(stack.subnet.nf_id) # "subnet"
Preprocessor Enhancement
With the preprocessor and Bind annotation, the syntax becomes even cleaner:
# coding: nf_autoid
from nf.core import App, Stack, Resource, Bind
class MyStack(Stack):
def __init__(self, vpc_cidr="10.0.0.0/16"):
super().__init__()
# Preprocessor transforms Bind annotations
self.vpc: Bind = Resource(type="aws_vpc", cidr_block=vpc_cidr)
# Becomes: self.vpc = Resource(type="aws_vpc", cidr_block=vpc_cidr)("vpc")
self.subnet: Bind = Resource(type="aws_subnet", vpc_id=self.vpc.output.id)
How It Works
1. Template Construct Creation
When you create a construct without binding:
- The construct stores its configuration in _deferred_config
- Sets _bound = False
- Creates an empty deferred-children list
- If created within another template construct's context, registers itself
2. Context Detection
Template constructs use Python's context manager protocol:
- with stack: pushes the stack onto a thread-local context stack
- Resources created within detect the template parent
- They register themselves in the parent's deferred-children list
3. Binding Process
When you call a template construct with (nf_id, scope):
1. Creates a new bound instance (not modifying the original)
2. Copies configuration from the original template
3. Performs the binding with the provided ID and scope
4. Automatically adopts and binds all deferred children
5. Returns the fully bound construct
4. Child Adoption
During binding, the parent: 1. Iterates through its deferred-children list 2. Finds the attribute name each child was assigned to 3. Binds each child with that attribute name as its ID 4. Sets the bound child back on the bound parent
Benefits
1. Clean Separation of Concerns
- Configuration logic separated from tree structure
- No mixing of infrastructure definition with binding mechanics
- Clear, predictable lifecycle
2. Natural Python Syntax
- Works like normal Python classes
- No special methods to override
- Intuitive
self.attribute = valuepatterns
3. Automatic Child Management
- No manual child registration
- Attribute names automatically become IDs
- Parent-child relationships handled transparently
4. Powerful Composition
- Lazy references between not-yet-bound resources
- Resources can reference each other before binding
- Circular dependencies handled gracefully
5. Type Safety
- Full type annotation support
- IDE autocomplete works naturally
- Static type checkers understand the pattern
Advanced Patterns
Factory Functions
def create_network_stack(cidr: str) -> Stack:
"""Factory that returns a stack template."""
stack = Stack()
with stack:
stack.vpc = Resource(type="aws_vpc", cidr_block=cidr)
stack.igw = Resource(type="aws_internet_gateway", vpc_id=stack.vpc.output.id)
return stack # Return the template
# Use the factory
app = App()("my-app")
network = create_network_stack("10.0.0.0/16")("network", scope=app)
Conditional Resources
class ConditionalStack(Stack):
def __init__(self, enable_monitoring=False):
super().__init__()
with self:
self.bucket = Resource(type="aws_s3_bucket", bucket="my-bucket")
if enable_monitoring:
self.alarm = Resource(type="aws_cloudwatch_metric_alarm", metric_name="BucketSize")
List Comprehensions
class MultiAZStack(Stack):
def __init__(self, availability_zones):
super().__init__()
with self:
self.vpc = Resource(type="aws_vpc", cidr_block="10.0.0.0/16")
# Create subnets for each AZ
self.subnets = [Resource(type="aws_subnet", vpc_id=self.vpc.output.id, cidr_block=f"10.0.{i}.0/24", availability_zone=az) for i, az in enumerate(availability_zones)]
Migration Guide
Old Pattern (Direct Binding)
# Old: Mixed configuration and binding
stack = Stack(scope=app, nf_id="my-stack")
vpc = Resource(scope=stack, nf_id="vpc", type="aws_vpc", cidr_block="10.0.0.0/16")
New Pattern (Deferred Binding)
# New: Separated configuration and binding
stack = Stack()("my-stack", scope=app)
with stack:
vpc = Resource(type="aws_vpc", cidr_block="10.0.0.0/16")("vpc")
With Preprocessor
# With preprocessor: Even cleaner
stack = Stack()("my-stack", scope=app)
with stack:
vpc: Bind = Resource(type="aws_vpc", cidr_block="10.0.0.0/16")
Implementation Details
The pattern is implemented in nf.core.constructs.base_construct.Construct:
__init__: Creates a construct template with configuration__call__: Binds construct to tree and adopts children- Context Manager: Enables scope detection for template constructs
- Child Adoption: Automatic binding of deferred children
The preprocessor (nf.codec.autoid.preprocessor) enhances the pattern by automatically injecting variable names when the Bind annotation is used.
Best Practices
- Always use context managers when creating resources in stack templates
- Let attribute names be IDs - they're descriptive and automatic
- Use factory functions for reusable infrastructure patterns
- Leverage lazy references for complex resource relationships
- Apply the preprocessor for the cleanest syntax
Conclusion
The Deferred Binding Pattern transforms infrastructure-as-code into natural, intuitive Python. By separating configuration from binding, it enables powerful composition patterns while maintaining simplicity and type safety. This pattern is foundational to netherframe's goal of bringing order to infrastructure chaos.