Custom Codec And Autoscope
This guide shows the practical Netherframe workflow for combining:
- the
nf_autoidsource codec BindandBindContextfor automaticnf_idinjectionwithblocks for app and stack scope@autoscopefor automaticnf_scopeinjection
Use this pattern when you want concise infrastructure code without repeating nf_scope= and nf_id= on every construct.
If you want to add the codec header across existing files first, use
nf encode.
What Each Piece Does
These features solve different problems:
# coding: nf_autoid: enables the source preprocessor for that Python fileBind: tells the preprocessor to injectnf_idfor annotated assignmentsBindContext: tells the preprocessor to injectnf_idforwith ... as namebindingswith App()andwith Stack(): make the app or stack the current scope for new constructs@autoscope: makes an app or stack subclass the current scope during its constructor
Short version:
- codec +
Bind/BindContextgives you automatic names withand@autoscopesupply the parent scope
To apply the codec header mechanically:
nf encode app.py
nf encode examples/
nf encode "pkg/**/*.py"
Important boundary:
@autoscopehelps when creating child constructs inside the__init__of anApporStacksubclass- it does not remove
nf_scopeandnf_idfrom your class constructor - it does not remove
super().__init__(nf_scope=nf_scope, nf_id=nf_id)
Recommended Pattern
#!/usr/bin/env python3
# coding: nf_autoid
from nf.core import App, Bind, BindContext, Output, Stack, autoscope
from nf.providers.hashicorp.aws import AwsProvider, Subnet, Vpc
@autoscope
class NetworkStack(Stack):
def __init__(self, *, nf_scope: App | None = None, nf_id: str | None = None, cidr: str) -> None:
super().__init__(nf_scope=nf_scope, nf_id=nf_id)
# From here on, @autoscope supplies nf_scope=self
# BindContext injects nf_id="aws"; Bind injects nf_id="vpc", "public_subnet" and "vpc_id"
with AwsProvider(region="us-east-1") as aws, BindContext:
self.vpc: Bind = Vpc(cidr_block=cidr)
self.public_subnet: Bind = Subnet(
vpc_id=self.vpc.output.id,
cidr_block="10.0.1.0/24",
availability_zone="us-east-1a",
)
self.vpc_id: Bind = Output(value=self.vpc.output.id)
with App() as app, BindContext:
network: Bind = NetworkStack(cidr="10.0.0.0/16")
app.synth()
Why This Works
In the example above:
with App() as app, BindContextinjectsnf_id="app"network: Bind = NetworkStack(...)injectsnf_id="network", and@autoscopesuppliesnf_scope=app, the construct entered withwith- once
super().__init__has run,@autoscopemakes the stack the current scope until its__init__returns, aswith self:would, so the provider,Vpc,SubnetandOutputgetnf_scope=self with AwsProvider(...) as aws, BindContextinjectsnf_id="aws"and makes it the provider of the resources in the blockself.vpc: Bind = Vpc(...)injectsnf_id="vpc"- the
NetworkStackconstructor still declaresnf_scopeandnf_id, and still passes them throughsuper(...)
That gives you the ergonomic shape most people want:
- explicit code structure
- automatic stable ids from variable names
- no repeated scope threading inside construct bodies
When To Use Bind
Use Bind on assignments where you want the codec to inject nf_id:
#!/usr/bin/env python3
# coding: nf_autoid
from nf.core import App, Bind, BindContext, Stack
from nf.providers.hashicorp.aws import AwsProvider, Subnet, Vpc
with App() as app, Stack() as stack, BindContext:
with AwsProvider(region="us-east-1") as aws, BindContext:
vpc: Bind = Vpc(cidr_block="10.0.0.0/16")
public_subnet: Bind = Subnet(
vpc_id=vpc.output.id,
cidr_block="10.0.1.0/24",
availability_zone="us-east-1a",
)
Without Bind, the current preprocessor does not inject nf_id for normal assignments.
When To Use BindContext
Use BindContext with with ... as name when you want the bound name to become the construct id:
# coding: nf_autoid
from nf.core import App, BindContext, Stack
with App() as app, Stack() as stack, BindContext:
...
A single BindContext covers both bindings in this with statement. Here the app
gets the ID app, and the stack gets the ID stack. The context managers enter in
order, so the app is already the current scope when the stack is created.
When To Use @autoscope
Use @autoscope on App and Stack subclasses when you want child constructs created inside __init__ to default to nf_scope=self:
# coding: nf_autoid
from nf.core import App, Bind, Stack, autoscope
from nf.providers.hashicorp.aws import Vpc
@autoscope
class Network(Stack):
def __init__(self, *, nf_scope: App | None = None, nf_id: str | None = None) -> None:
super().__init__(nf_scope=nf_scope, nf_id=nf_id)
self.vpc: Bind = Vpc(cidr_block="10.0.0.0/16")
What @autoscope does:
- when the class is created without
nf_scope, it supplies the current scope (the innermost construct entered withwith) - for an
ApporStacksubclass, the construct becomes the current scope oncesuper().__init__has run, until its__init__returns;with self:in the body is no longer needed, and awith other_stack:block or an explicitnf_scope=still wins - methods called after
__init__returns are not covered: usewith self:or passnf_scope=selfthere
It is still your responsibility to:
- keep
nf_scopeandnf_idin the subclass constructor signature when the base construct expects them, defaulting toNoneso type checkers accept the codec's call sites (see Type Checking) - pass those values into
super().__init__(nf_scope=nf_scope, nf_id=nf_id)
@autoscope does not rewrite your constructor signature or your super(...) call.
Construct Subclasses
A resource belongs to a stack, so a plain Construct subclass is not made the scope of what its __init__ creates: resources created there get the current scope where the construct itself is created, which must be a stack.
#!/usr/bin/env python3
# coding: nf_autoid
from nf.core import App, Bind, BindContext, Construct, Stack, autoscope
from nf.providers.hashicorp.aws import AwsProvider, Vpc
@autoscope
class Network(Construct):
def __init__(self, *, nf_scope: Construct | None = None, nf_id: str | None = None, cidr: str) -> None:
super().__init__(nf_scope=nf_scope, nf_id=nf_id)
# The Vpc belongs to the stack the Network is created in
self.vpc: Bind = Vpc(cidr_block=cidr)
with App() as app, Stack() as stack, BindContext:
with AwsProvider(region="us-east-1") as aws, BindContext:
network: Bind = Network(cidr="10.0.0.0/16")
assert network.vpc.nf_scope is stack
Do not use with self: in a Construct subclass to place resources: a resource whose scope is not a stack is rejected.
When To Stay Explicit
Stay explicit with nf_scope or nf_id when the name or parent is not obvious from source structure.
Common cases:
- loops that create many resources
- list/dict comprehensions
- helper functions that create resources outside an autoscoped
__init__ - places where a stable public id matters more than the variable name
Example:
from nf.core import App, Stack
from nf.providers.hashicorp.aws import AwsProvider, Subnet, Vpc
app = App()
stack = Stack(nf_scope=app, nf_id="explicit-subnets")
provider = AwsProvider(nf_scope=stack, nf_id="aws", region="us-east-1")
with provider:
vpc = Vpc(
nf_scope=stack,
nf_id="vpc",
cidr_block="10.0.0.0/16",
)
for index in range(3):
Subnet(
nf_scope=stack,
nf_id=f"public-subnet-{index + 1}",
vpc_id=vpc.output.id,
cidr_block=f"10.0.{index + 1}.0/24",
availability_zone="us-east-1a",
)
Running Code That Uses nf_autoid
The nf CLI pre-registers the codec before importing encoded modules, so the common CLI workflows already handle this.
Python only supports one active source encoding per file. You can use
# coding: nf_autoid or # encoding: nf_autoid, but you cannot stack multiple
encoding cookies to run multiple codecs in sequence.
If you run encoded modules directly with plain Python and hit:
LookupError: unknown encoding: nf_autoid
register the codec before importing those modules:
from nf.codec.autoid import register_codec
register_codec()
Installed environments also ship a .pth file that auto-registers the codec, but the manual registration snippet above is the direct fallback when you need one.
Troubleshooting
IDs Are Not Being Injected
Check these first:
- the file starts with
# coding: nf_autoid - assignment sites use
: Bind with ... as namesites includeBindContext
nf_scope Is Missing
@autoscope only helps when there is an active construct context.
If you are:
- outside the
__init__of an autoscopedApporStackand outside anywithblock - inside a helper function with no active context
- creating cross-scope resources intentionally
pass nf_scope= explicitly.
I Want A Specific Stable ID
Set nf_id explicitly. Automatic naming is convenient, but explicit ids are still the right tool when the externally meaningful name should not depend on the Python variable name.