Skip to content

Generic Tokens Proposal for netherframe

Overview

This proposal introduces generic tokens (Token[T]) to provide better type safety and IDE support in netherframe.

Benefits

  1. Type Safety: The type system knows what type a token will resolve to
  2. Better IDE Support: Autocomplete and type hints work correctly
  3. Clearer APIs: Function signatures explicitly show token types
  4. Compile-Time Checking: Type errors caught before runtime

Implementation Design

Core Token Class

from typing import Generic, TypeVar

T = TypeVar("T")


class Token(Generic[T]):
    """Type-safe token representing a value that will be resolved later."""

    def __init__(self, resolvable: Resolvable[T]) -> None:
        self._resolvable = resolvable
        self._encoded: str | float | list[str] | None = None

    def resolve(self, context: Any) -> T:
        """Resolve this token to its concrete value."""
        return self._resolvable.resolve(context)

Updated Resource Properties

class Resource:
    @property
    def ref_id(self) -> Token[str]:
        """Token reference to the resource's ID attribute."""
        return Token(ResourceAttribute(self, "id"))

    def ref_attribute(self, name: str) -> Token[str]:
        """Get a token reference to a string attribute."""
        return Token(ResourceAttribute(self, name))

    def ref_attribute_as_number(self, name: str) -> Token[float]:
        """Get a token reference to a numeric attribute."""
        return Token(ResourceAttributeNumber(self, name))

    def ref_attribute_as_list(self, name: str) -> Token[list[str]]:
        """Get a token reference to a list attribute."""
        return Token(ResourceAttributeList(self, name))

Updated Variable Properties

class Variable:
    @property
    def ref(self) -> Token[str]:
        """Token reference to the variable's value."""
        return Token(VariableReference(self))

    @property
    def ref_as_number(self) -> Token[float]:
        """Token reference as a number."""
        return Token(VariableReferenceNumber(self))

    @property
    def ref_as_list(self) -> Token[list[str]]:
        """Token reference as a list."""
        return Token(VariableReferenceList(self))

Lazy Values with Types

class Lazy:
    @staticmethod
    def string(producer: Callable[[], str]) -> Token[str]:
        """Create a lazy string value."""
        return Token(LazyValue(producer))

    @staticmethod
    def number(producer: Callable[[], float]) -> Token[float]:
        """Create a lazy number value."""
        return Token(LazyValue(producer))

    @staticmethod
    def list(producer: Callable[[], list[T]]) -> Token[list[T]]:
        """Create a lazy list value."""
        return Token(LazyValue(producer))

Usage Examples

Basic Usage

# Type-safe token references
bucket = Resource(type="aws_s3_bucket", bucket="my-bucket")
bucket_id: Token[str] = bucket.ref_id  # Type checker knows this is Token[str]

# Numeric tokens
instance = Resource(type="aws_instance", instance_type="t2.micro")
cpu_count: Token[float] = instance.ref_attribute_as_number("vcpu_count")

# List tokens
security_group = Resource(type="aws_security_group", name="web")
ingress_rules: Token[list[str]] = security_group.ref_attribute_as_list("ingress")

With Functions

from nf.core.functions import Fn


# Function parameters can accept Token[T] or T
def create_url(bucket_name: str | Token[str], path: str) -> Token[str]:
    return Fn.format("https://{}.s3.amazonaws.com/{}", bucket_name, path)


# Usage
bucket = Resource(type="aws_s3_bucket", bucket="my-bucket")
url = create_url(bucket.ref_id, "index.html")  # Type-safe!

Type-Safe Conditionals

# Conditional with proper types
def conditional_value(condition: bool | Token[bool], true_val: str | Token[str], false_val: str | Token[str]) -> Token[str]:
    return Fn.conditional(condition, true_val, false_val)


# Usage
env = Variable(type="string", default="dev")
bucket_name = conditional_value(Fn.equals(env.ref, "prod"), "prod-bucket", "dev-bucket")  # Returns Token[str]

Complex Types

# Token of custom type
@dataclass
class BucketConfig:
    name: str
    versioning: bool
    tags: dict[str, str]


def get_bucket_config() -> Token[BucketConfig]:
    return Lazy.any(lambda: BucketConfig(name="my-bucket", versioning=True, tags={"env": "prod"}))


# Usage
config: Token[BucketConfig] = get_bucket_config()

Migration Strategy

Phase 1: Add Generic Token Support

  • Implement Token[T] alongside existing token system
  • Update return types to use Token[T]
  • Maintain backward compatibility

Phase 2: Deprecate Old Methods

  • Mark TokenEncoding.as_string() etc. as deprecated
  • Provide migration guide
  • Add warnings for old usage

Phase 3: Remove Old System

  • Remove static token methods
  • Clean up redundant code
  • Full generic token system

Backward Compatibility

To maintain compatibility during migration:

# Old style (still works)
bucket_id = TokenEncoding.as_string(ResourceAttribute(bucket, "id"))

# New style (recommended)
bucket_id = bucket.ref_id  # Returns Token[str]

# Both produce the same encoded token

Type Union Pattern

For functions that accept both resolved and token values:

from typing import Union

# Type alias for convenience
StrToken = Union[str, Token[str]]
NumToken = Union[float, int, Token[float]]
ListToken = Union[list[T], Token[list[T]]]


# Usage in function signatures
def create_resource(name: StrToken, size: NumToken, tags: ListToken[str]) -> Resource:
    # Implementation handles both cases
    pass

Benefits for Users

  1. Better IDE Experience

    bucket.ref_id.  # IDE shows Token[str] methods
    instance.ref_attribute_as_number("cpu").  # IDE knows this is Token[float]
    

  2. Type Checking

    # This would be caught by type checker
    cpu_count: Token[str] = instance.ref_attribute_as_number("cpu")  # Error!
    

  3. Clear Documentation

    def process_bucket(bucket_id: Token[str]) -> Token[str]:
        """Process a bucket ID token."""
        # Clear that this expects a token, not a resolved string
    

  4. Safer Refactoring

  5. Changing token types is caught at compile time
  6. IDE can help with refactoring

Implementation Notes

  1. Token Encoding: The encoding mechanism remains the same, just wrapped in type-safe classes
  2. Resolution: The resolution process is unchanged, but now type-aware
  3. Performance: No runtime performance impact, only compile-time type checking
  4. Compatibility: Can coexist with current system during migration

Conclusion

Generic tokens provide significant benefits for type safety and developer experience without adding complexity for users. The migration can be done gradually while maintaining full backward compatibility.