Skip to content

Custom Codec And Autoscope

This guide shows the practical Netherframe workflow for combining:

  • the nf_autoid source codec
  • Bind and BindContext for automatic nf_id injection
  • with blocks for app and stack scope
  • @autoscope for automatic nf_scope injection

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 file
  • Bind: tells the preprocessor to inject nf_id for annotated assignments
  • BindContext: tells the preprocessor to inject nf_id for with ... as name bindings
  • with App() and with 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 / BindContext gives you automatic names
  • with and @autoscope supply the parent scope

To apply the codec header mechanically:

nf encode app.py
nf encode examples/
nf encode "pkg/**/*.py"

Important boundary:

  • @autoscope helps when creating child constructs inside the __init__ of an App or Stack subclass
  • it does not remove nf_scope and nf_id from your class constructor
  • it does not remove super().__init__(nf_scope=nf_scope, nf_id=nf_id)
#!/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, BindContext injects nf_id="app"
  • network: Bind = NetworkStack(...) injects nf_id="network", and @autoscope supplies nf_scope=app, the construct entered with with
  • once super().__init__ has run, @autoscope makes the stack the current scope until its __init__ returns, as with self: would, so the provider, Vpc, Subnet and Output get nf_scope=self
  • with AwsProvider(...) as aws, BindContext injects nf_id="aws" and makes it the provider of the resources in the block
  • self.vpc: Bind = Vpc(...) injects nf_id="vpc"
  • the NetworkStack constructor still declares nf_scope and nf_id, and still passes them through super(...)

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 with with)
  • for an App or Stack subclass, the construct becomes the current scope once super().__init__ has run, until its __init__ returns; with self: in the body is no longer needed, and a with other_stack: block or an explicit nf_scope= still wins
  • methods called after __init__ returns are not covered: use with self: or pass nf_scope=self there

It is still your responsibility to:

  • keep nf_scope and nf_id in the subclass constructor signature when the base construct expects them, defaulting to None so 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 name sites include BindContext

nf_scope Is Missing

@autoscope only helps when there is an active construct context.

If you are:

  • outside the __init__ of an autoscoped App or Stack and outside any with block
  • 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.