Local-Only AST Transformation for Variable Name Detection
Overview
netherframe provides local-only AST transformation as an opt-in performance optimization for automatic variable name detection. Unlike global import hooks, this approach gives you fine-grained control over which code gets transformed.
Why Local-Only?
- Explicit Control: You decide exactly which modules/functions use AST transformation
- No Global Side Effects: Doesn't affect third-party libraries or system modules
- Better Testing: Easier to test with and without transformation
- Debugging: Can selectively enable for performance-critical sections
Usage Patterns
Context Manager (Recommended)
Use ast_transform() to transform modules imported within the context:
from nf.core import ast_transform
with ast_transform():
# Modules imported here will be transformed
import my_infrastructure
my_infrastructure.create_resources()
Decorator for Functions
Use @with_ast_transform to transform imports within a function:
from nf.core import with_ast_transform
@with_ast_transform
def setup_infrastructure():
import my_resources # This import will be transformed
return my_resources.create_stack()
Direct Source Transformation
For advanced use cases, transform source code directly:
from nf.core import transform_source
source = """
vpc = Resource(stack, type="aws_vpc")
"""
transformed = transform_source(source)
Real-World Example
from nf.core import App, Stack, Resource, ast_transform, autoscope
# Without AST transformation - uses stack introspection
app = App()
regular_stack = Stack(app) # ID detected via stack introspection
# With AST transformation - faster for many resources
with ast_transform():
# Import your infrastructure modules here
import my_large_infrastructure
# All Resource creation in the imported module
# will use AST-based detection
my_large_infrastructure.deploy(app)
Performance Considerations
When to Use AST Transformation
✅ Good Use Cases: - Creating many resources (100+) in a loop - Infrastructure modules with complex resource hierarchies - Performance-critical deployment scripts - Code generation scenarios
❌ Not Necessary For: - Simple scripts with few resources - Interactive development/debugging - One-off resource creation
Performance Example
from nf.core import ast_transform
import time
# Measure without AST
start = time.time()
# ... create 1000 resources ...
print(f"Stack introspection: {time.time() - start}s")
# Measure with AST
with ast_transform():
import my_bulk_resources
start = time.time()
my_bulk_resources.create_thousand_resources()
print(f"AST transformation: {time.time() - start}s")
How It Works
- Import Interception: When you use
ast_transform(), it temporarily installs an import hook - AST Parsing: Python source files are parsed into Abstract Syntax Trees
- Transformation: Variable assignments like
vpc = Resource(...)are wrapped - Code Generation: The transformed AST is compiled back to Python bytecode
- Cleanup: The import hook is removed when leaving the context
Limitations
- Import Time Only: Only affects modules imported within the transformation context
- Source Files Only: Binary extensions (.so, .pyd) cannot be transformed
- Dynamic Code:
eval()andexec()within transformed modules won't be transformed
Testing
Writing Tests with AST Transformation
import pytest
from nf.core import ast_transform
class TestMyInfrastructure:
def test_with_ast_transform(self):
with ast_transform():
import my_test_module
# Test the module with AST transformation
result = my_test_module.create_resources()
assert result.vpc.nf_id == "vpc"
Comparing Behaviors
def test_both_modes():
# Test with stack introspection
vpc1 = Resource(stack, type="aws_vpc")
assert vpc1.nf_id == "vpc1"
# Test with AST transformation
with ast_transform():
import test_resources
vpc2 = test_resources.create_vpc(stack)
assert vpc2.nf_id == "vpc"
Best Practices
- Module-Level Transformation: Transform entire infrastructure modules rather than snippets
- Profile First: Measure if AST transformation actually helps your use case
- Document Usage: Comment why AST transformation is used in specific places
- Test Both Ways: Ensure your code works with and without transformation
Configuration
Environment Variables
netherframe reads no environment variables, and the variables this design once used are gone.
Automatic naming is now the nf_autoid source codec (# coding: nf_autoid; see the
Preprocessor Quick Reference); nf synth --no-auto-naming turns it off for one run.
Programmatic Control
from nf.core import enable_ast_transform, disable_ast_transform
# Disable AST transformation features
disable_ast_transform()
# Re-enable AST transformation features
enable_ast_transform()
Migration Guide
If you were using global AST transformation before:
# Old (global)
enable_ast_transform() # Affected all imports globally
import my_module
# New (local)
with ast_transform():
import my_module # Only this import is transformed
Troubleshooting
Import Not Transformed
- Ensure the import happens inside the
ast_transform()context - Check that the module hasn't been imported before (use
importlib.reloadif needed) - Verify AST transformation is enabled:
is_ast_transform_enabled()
Performance Not Improved
- AST transformation helps most with many resources (100+)
- Profile your specific use case - stack introspection might be fast enough
- Consider if the import overhead outweighs the benefits
Debugging Transformed Code
- Use
transform_source()to see the transformed code - Set breakpoints in the original source - debuggers handle the transformation
- Disable transformation temporarily for debugging