Skip to content

API Reference

This reference is automatically generated from docstrings in the source code.

validate_pfig() does not materialize providers or execute the entrypoint, but it does import Python modules while resolving configuration imports. Treat validation like running trusted code when imports are involved.

External requirement scope

Execution and validate_pfig() require only the selected entrypoint's effective inputs; run() also checks an enabled __snapshot__ directive before construction. instantiate() checks its requested binding after fresh-call kwargs apply. Unused declarations and supplied unused values are retained. Supplying None satisfies a declaration.

Rootless compile_pfig() reports missing inputs across all declarations, even when a default entrypoint exists. allow_missing_externals=True suppresses missing-input diagnostics for incomplete validation or packaging; it does not permit materialization of unresolved dependencies.

Core Functions

Python run() creates snapshots only when snapshot_dir is supplied or the root config defines __snapshot__; unlike CLI pfig run, it does not default to ./snapshots. Python run() can evaluate computed snapshot directives.

run

run(path: str | Path, *, entrypoint: str | None = None, externals: Dict[str, Any] | None = None, profile_paths: Sequence[str | Path | ProfileSpec] | None = None, snapshot_dir: str | Path | None = None, no_snapshot: bool = False, strict: bool = False) -> Any

Execute a pfig configuration file from Python.

Handles parsing, planning, materialization, and execution in a single call. Unlike CLI pfig run, this API does not create snapshots by default: set snapshot_dir or define a root __snapshot__ binding to enable them. Computed __snapshot__ expressions are supported by this API.

PARAMETER DESCRIPTION
path

Path to the .pfig configuration file

TYPE: str | Path

entrypoint

Optional override: binding name or attribute path (outer.data.copy). If None, uses the entrypoint binding.

TYPE: str | None DEFAULT: None

externals

Optional external values to satisfy external declarations

TYPE: Dict[str, Any] | None DEFAULT: None

profile_paths

Optional paths to profile files to load

TYPE: Sequence[str | Path | ProfileSpec] | None DEFAULT: None

snapshot_dir

Overrides __snapshot__. A timestamped subdirectory is created inside.

TYPE: str | Path | None DEFAULT: None

no_snapshot

Skip snapshot creation even when __snapshot__ is set.

TYPE: bool DEFAULT: False

strict

If True, treat validation warnings as errors

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Any

Result of calling the entrypoint function

RAISES DESCRIPTION
ExecutionError

If entrypoint is missing, not callable, or execution fails

ParseError

If config parsing fails

FileNotFoundError

If the path does not exist

Example
from pfig import run

# Simple execution
result = run("config.pfig")

# With externals
result = run("config.pfig", externals={"batch_size": 64})

# With snapshotting from the config directive
# __snapshot__ = @output_dir + "/snapshots"
result = run("config.pfig", externals={"output_dir": "./runs"})

instantiate

instantiate(name: str, path: Union[str, Path] | None = None, source: str | None = None, *, fresh: bool = False, call_kwargs: Optional[Dict[str, Any]] = None, externals: Optional[Dict[str, Any]] = None, profile_paths: Sequence[str | Path | ProfileSpec] | None = None, strict: bool = False) -> Any

Instantiate a specific binding from a pfig configuration.

The whole configuration is parsed and compiled (including Python imports and compile-time signature checks). Only objects reachable from the requested binding are materialized, and required externals are scoped to that sub-DAG. No entrypoint is required.

PARAMETER DESCRIPTION
name

Binding path to instantiate (e.g. "trainer", "alias/model").

TYPE: str

path

Filesystem path to a .pfig file. Mutually exclusive with source.

TYPE: Union[str, Path] | None DEFAULT: None

source

pfig source code provided inline. Mutually exclusive with path.

TYPE: str | None DEFAULT: None

fresh

If False, behaves like @name (shared instance). If True, behaves like @name(...) (fresh instance).

TYPE: bool DEFAULT: False

call_kwargs

Keyword arguments to overlay for a fresh construction of the provider; providing call_kwargs implies fresh=True.

TYPE: Optional[Dict[str, Any]] DEFAULT: None

externals

External values to satisfy external declarations. Applied after profiles and validated against declarations.

TYPE: Optional[Dict[str, Any]] DEFAULT: None

profile_paths

List of profile files to load in order. Later profiles override earlier ones. Values from externals override all profile values.

TYPE: Sequence[str | Path | ProfileSpec] | None DEFAULT: None

strict

If True, treat validation warnings as errors

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Any

The materialized object for the specified binding.

RAISES DESCRIPTION
ExecutionError

If the binding is missing/not found or materialization fails.

ParseError

If config parsing fails.

FileNotFoundError

If the path does not exist.

Examples:

Basic usage:

from pfig import instantiate

config = '''
from collections import Counter
word_counter = Counter()
'''
counter = instantiate("word_counter", source=config)
isinstance(counter, Counter)  # True

Fresh instance with kwargs (overlays imply fresh):

fresh_counter = instantiate(
    "word_counter",
    source=config,
    call_kwargs={"iterable": ["a", "b", "a"]},
)

execute_pfig

execute_pfig(ast_file: PFigFile, entrypoint: str | None = None, filename: str | None = None, externals: Dict[str, Any] | None = None, profile_paths: Sequence[str | Path | ProfileSpec] | None = None, strict: bool = False) -> Any

Execute a parsed pfig AST and return the result.

This is a convenience wrapper around execute_pfig_with_metadata() that returns just the execution result. Use execute_pfig_with_metadata() if you need access to execution metadata (e.g., for validation or snapshotting).

PARAMETER DESCRIPTION
ast_file

Parsed pfig AST

TYPE: PFigFile

entrypoint

Optional override: binding name or attribute path (outer.data.copy). If None, uses the entrypoint binding.

TYPE: str | None DEFAULT: None

filename

Optional filename for error reporting

TYPE: str | None DEFAULT: None

externals

Optional external values to override

TYPE: Dict[str, Any] | None DEFAULT: None

profile_paths

Optional paths to profile files to load

TYPE: Sequence[str | Path | ProfileSpec] | None DEFAULT: None

strict

If True, treat validation warnings as errors

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Any

Result of calling the entrypoint function

RAISES DESCRIPTION
ExecutionError

If entrypoint is missing, not callable, or execution fails

Example
from pfig import parse_pfig_source, execute_pfig

config = '''
from collections import OrderedDict
data = OrderedDict(a=1, b=2)
__entrypoint__ = @data.keys
'''
ast = parse_pfig_source(config)
result = execute_pfig(ast)  # Returns odict_keys(['a', 'b'])

validate_pfig

validate_pfig(ast_file: PFigFile, entrypoint: str | None = None, filename: str | None = None, externals: Dict[str, Any] | None = None, profile_paths: Sequence[str | Path | ProfileSpec] | None = None, strict: bool = False, allow_missing_externals: bool = False) -> 'ExecutionMetadata'

Validate a pfig configuration without materialization.

Performs structural validation including: - Syntax validation (via parsing, done before this function) - Import resolution - Signature validation (missing/unknown kwargs) - Dependency resolution (topological sort, cycle detection) - Missing-kwargs-usage checks - Entrypoint callable check (static)

Does NOT materialize providers or call the entrypoint. Compilation still resolves import statements via Python's import system, so module-level side effects in imported modules may occur during validation.

PARAMETER DESCRIPTION
ast_file

Parsed pfig AST

TYPE: PFigFile

entrypoint

Optional override: binding name or attribute path (outer.data.copy). If None, uses the entrypoint binding.

TYPE: str | None DEFAULT: None

filename

Optional filename for error reporting

TYPE: str | None DEFAULT: None

externals

Optional external values to override

TYPE: Dict[str, Any] | None DEFAULT: None

profile_paths

Optional paths to profile files to load

TYPE: Sequence[str | Path | ProfileSpec] | None DEFAULT: None

strict

If True, treat validation warnings as errors

TYPE: bool DEFAULT: False

allow_missing_externals

If True, permit incomplete validation without required inputs. Otherwise requirements follow the selected entrypoint, not all declarations. This flag never permits unresolved inputs to be materialized.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
'ExecutionMetadata'

ExecutionMetadata with compiled data, entrypoint info, reachable bindings, etc.

'ExecutionMetadata'

The materialized dict is empty and result is None (no objects are constructed).

RAISES DESCRIPTION
ExecutionError

If validation fails (missing kwargs, non-callable entrypoint, etc.)

compile_pfig

compile_pfig(ast_file: PFigFile, filename: str | None = None, externals: Dict[str, Any] | None = None, profile_paths: Sequence[str | Path | ProfileSpec] | None = None, strict: bool = False, allow_missing_externals: bool = False) -> Tuple[Dict[str, Any], List[ValidationIssue]]

Compile a pfig configuration without requiring an entrypoint.

Runs the Parse -> Compose -> Validate phases (import resolution, include resolution, signature validation, duplicate-binding checks, etc.) but skips the entrypoint-dependent phases (reachability analysis, missing-kwargs-usage, graph materialization).

This is the recommended entry point for editor tooling (LSP servers, linters) where the file being checked may not define __entrypoint__.

PARAMETER DESCRIPTION
ast_file

Parsed pfig AST

TYPE: PFigFile

filename

Optional filename for error reporting and relative include resolution

TYPE: str | None DEFAULT: None

externals

Optional external values to override

TYPE: Dict[str, Any] | None DEFAULT: None

profile_paths

Optional paths to profile files to load

TYPE: Sequence[str | Path | ProfileSpec] | None DEFAULT: None

strict

If True, treat validation warnings as errors

TYPE: bool DEFAULT: False

allow_missing_externals

If True, suppress whole-file missing-input diagnostics. Unlike execution validation, rootless compilation checks all declarations.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Dict[str, Any]

Tuple of (compiled_data, issues) where compiled_data is the compiler

List[ValidationIssue]

output dict and issues is a list of ValidationIssue objects.

Tuple[Dict[str, Any], List[ValidationIssue]]

Does not raise on validation problems — all issues are returned in

Tuple[Dict[str, Any], List[ValidationIssue]]

the list.

execute_pfig_with_metadata

execute_pfig_with_metadata(ast_file: PFigFile, entrypoint: str | None = None, filename: str | None = None, externals: Dict[str, Any] | None = None, profile_paths: Sequence[str | Path | ProfileSpec] | None = None, strict: bool = False, allow_missing_externals: bool = False, compile_only: bool = False) -> ExecutionMetadata

Execute pfig configuration and return full execution metadata.

This is the core execution function that orchestrates the complete pipeline:

  1. Resolves entrypoint (CLI takes precedence over entrypoint)
  2. Plans by finding bindings reachable from entrypoint
  3. Materializes only the minimal required set of objects
  4. Validates entrypoint is callable
  5. Calls the entrypoint

For validation without materialization or execution, use :func:validate_pfig.

Returns ExecutionMetadata with compiled data, materialized objects, and result. Used by CLI and by execute_pfig() for simple execution.

PARAMETER DESCRIPTION
ast_file

Parsed pfig AST

TYPE: PFigFile

entrypoint

Optional override: binding name or attribute path (outer.data.copy). If None, uses the entrypoint binding.

TYPE: str | None DEFAULT: None

filename

Optional filename for error reporting

TYPE: str | None DEFAULT: None

externals

Optional external values to override

TYPE: Dict[str, Any] | None DEFAULT: None

profile_paths

Optional paths to profile files to load

TYPE: Sequence[str | Path | ProfileSpec] | None DEFAULT: None

strict

If True, treat validation warnings as errors

TYPE: bool DEFAULT: False

allow_missing_externals

Packaging compatibility flag. File discovery preserves unresolved inputs; execution always checks required inputs.

TYPE: bool DEFAULT: False

compile_only

If True, only compile (skip planning/materialization) for file discovery

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
ExecutionMetadata

ExecutionMetadata with compiled data, materialized objects, and execution result

RAISES DESCRIPTION
ExecutionError

If entrypoint is missing, not callable, or execution fails

Example
from pfig import parse_pfig_source
from pfig.execution import execute_pfig_with_metadata

config = '''
from collections import OrderedDict
settings = OrderedDict(batch_size=64, lr=0.001)
__entrypoint__ = @settings.keys
'''
ast = parse_pfig_source(config)
metadata = execute_pfig_with_metadata(ast)
metadata.result  # odict_keys(['batch_size', 'lr'])

parse_pfig_source

parse_pfig_source(source: str, *, filename: str | None = None, with_index: Literal[False] = False) -> PFigFile
parse_pfig_source(source: str, *, filename: str | None = None, with_index: Literal[True]) -> 'ParseResult'
parse_pfig_source(source: str, *, filename: str | None = None, with_index: bool = False) -> Union[PFigFile, 'ParseResult']

Parse pfig configuration source code into an Abstract Syntax Tree.

This function takes pfig DSL source code and produces a structured AST representation following the formal grammar defined in the pfig v1 specification. The parser supports all pfig language constructs including imports, includes, externals, overrides, bindings, and expressions.

PARAMETER DESCRIPTION
source

The pfig source code to parse as a string. This should be valid pfig DSL syntax including statements like: - Import statements: import torch, from collections import defaultdict - Include statements: include "./base.pfig" as base - External declarations: external output_dir - Override statements: override batch_size = 128 - Bindings: model = torch.nn.Linear(input_dim=784, output_dim=10) - Provider references: optimizer = @model, fresh_model = @model()

TYPE: str

filename

Optional filename for error reporting. If provided, parse errors will include this filename in their error messages (e.g., "config.pfig:5:10: Unexpected token"). If None, errors will show "" as the filename. This parameter is keyword-only.

TYPE: str | None DEFAULT: None

with_index

If True, also build a DocumentIndex and return ParseResult. The index is useful for LSP tooling (go-to-definition, hover, completions). This parameter is keyword-only.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Union[PFigFile, 'ParseResult']

PFigFile when with_index=False, or ParseResult(ast, index) when with_index=True.

RAISES DESCRIPTION
LexerError

If the source contains invalid tokens, malformed strings, or other lexical errors.

ParseError

If the source contains valid tokens but invalid syntax according to the pfig grammar.

Examples:

Basic usage with just source code:

>>> ast = parse_pfig_source('batch_size = 64')
>>> len(ast.statements)
1

With index for LSP:

>>> result = parse_pfig_source('batch_size = 64', with_index=True)
>>> result.ast.statements
>>> result.index.binding_defs['batch_size']
Note

The parser follows the pfig v1 specification grammar and supports the complete DSL including nested expressions, provider references, and all statement types. For execution of the parsed AST, use the execute_pfig function from the execution module.

parse_config_file

parse_config_file(path: Union[str, Path]) -> PFigFile

Parse a pfig configuration file into an AST.

PARAMETER DESCRIPTION
path

path to a pfig file

TYPE: Union[str, Path]

RETURNS DESCRIPTION
PFigFile

Parsed PFigFile AST

RAISES DESCRIPTION
FileNotFoundError

If Path doesn't exist

ParseError

If parsing fails

get_materialized_bindings

get_materialized_bindings(ast_file: PFigFile, entrypoint: str | None = None, filename: str | None = None, externals: Dict[str, Any] | None = None, profile_paths: Sequence[str | Path | ProfileSpec] | None = None, strict: bool = False) -> Dict[str, Any]

Get all materialized bindings reachable from entrypoint without executing it.

This function is primarily for testing and debugging purposes. It performs the same materialization as execute_pfig() but returns the materialized bindings dictionary instead of calling the entrypoint.

PARAMETER DESCRIPTION
ast_file

Parsed pfig AST

TYPE: PFigFile

entrypoint

Optional override: binding name or attribute path (outer.data.copy). If None, uses the entrypoint binding.

TYPE: str | None DEFAULT: None

filename

Optional filename for error reporting

TYPE: str | None DEFAULT: None

externals

Optional external values to override

TYPE: Dict[str, Any] | None DEFAULT: None

profile_paths

Optional paths to profile files to load

TYPE: Sequence[str | Path | ProfileSpec] | None DEFAULT: None

strict

If True, treat validation warnings as errors

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Dict[str, Any]

Dictionary mapping binding names to materialized objects (only reachable ones)

RAISES DESCRIPTION
ExecutionError

If entrypoint is missing, not callable, or materialization fails


LSP API (for editor integration)

index_from_ast

index_from_ast(ast: PFigFile, filename: str, source: str, uri: Optional[str] = None) -> DocumentIndex

Build a DocumentIndex from a parsed AST.

PARAMETER DESCRIPTION
ast

Parsed PFigFile AST

TYPE: PFigFile

filename

Path to source file (for resolving relative includes)

TYPE: str

source

Full source text (needed for computing ranges)

TYPE: str

uri

Optional file:// URI. If None, constructed from filename.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION
DocumentIndex

DocumentIndex with all structural info and LSP ranges (0-based)

node_at_position

node_at_position(index: DocumentIndex, pos: dict) -> Optional[dict]

Return {kind, name, range} for the node at LSP position pos, or None.

PARAMETER DESCRIPTION
index

DocumentIndex to search

TYPE: DocumentIndex

pos

LSP Position {"line": int, "character": int} (0-based)

TYPE: dict

RETURNS DESCRIPTION
Optional[dict]

dict with kind, name, range, or None if nothing at position

resolve_include_path

resolve_include_path(target_path: str, current_filename: str) -> Optional[str]

Resolve an include path to an absolute file path (LSP-friendly API).

PARAMETER DESCRIPTION
target_path

Explicit filesystem path from source, e.g. "./consts.pfig"

TYPE: str

current_filename

Absolute path of the file containing the include

TYPE: str

RETURNS DESCRIPTION
Optional[str]

Absolute path to the resolved file, or None if not found.

resolve_provider_ref

resolve_provider_ref(name: str, current_filename: str, index: DocumentIndex, resolved_includes: dict[str, str]) -> Optional[tuple[str, dict]]

Resolve a provider ref to its definition location.

PARAMETER DESCRIPTION
name

e.g. "epochs" or "consts/epochs"

TYPE: str

current_filename

File containing the ref

TYPE: str

index

DocumentIndex of current file

TYPE: DocumentIndex

resolved_includes

Pre-resolved include paths (target_path -> resolved_abs_path)

TYPE: dict[str, str]

RETURNS DESCRIPTION
Optional[tuple[str, dict]]

(uri, range) of the definition, or None.

Optional[tuple[str, dict]]

For overrides: returns the override location first.

ParseResult dataclass

ParseResult(ast: PFigFile, index: DocumentIndex)

Result of parsing with index. Returned by parse_pfig_source(with_index=True).

DocumentIndex dataclass

DocumentIndex(binding_defs: Dict[str, BindingDef] = dict(), external_defs: Dict[str, BindingDef] = dict(), refs: List[RefInfo] = list(), imports: Dict[str, ImportBinding] = dict(), includes: List[IncludeEdge] = list(), call_sites: List[CallSite] = list(), externals: List[str] = list(), overrides: Dict[str, dict] = dict())

Structural index of a pfig document for LSP consumption.

See LSP API Reference for a full integration guide.


Snapshot Functions

create_snapshot

create_snapshot(compiled: Dict[str, Any], entrypoint: str, output_dir: str | Path, pfig_files: Optional[Sequence[str | Path]] = None, externals: Optional[Dict[str, Any]] = None, external_sources: Optional[Dict[str, str]] = None, reachable_names: Optional[Set[str]] = None, run_id: Optional[str] = None, include_payload: bool = True, file_origins: Optional[Dict[str, Any]] = None, entry_path: Optional[Path] = None, profile_paths: Optional[Sequence[Path]] = None, profile_file_origins: Optional[Dict[str, Any]] = None, base_commit: Optional[str] = None) -> str | Path

Create a complete snapshot for a pfig run.

This creates the following artifacts:

  • log.json: The IR graph with resolved defaults
  • payload/config_bundle.tar.gz: Portable config bundle (all .pfig files)
  • payload/requirements.lock: pip freeze output
  • payload/patches/: Git patch series for reproducibility
    • 0001-*.patch, 0002-*.patch, ...: Individual commit patches (git format-patch)
    • dirty.patch: Uncommitted changes (if working tree is dirty)
PARAMETER DESCRIPTION
compiled

Compiled configuration data from ASTCompiler

TYPE: Dict[str, Any]

entrypoint

Name of the entrypoint binding

TYPE: str

output_dir

Base directory for snapshots

TYPE: str | Path

pfig_files

List of .pfig files to include in payload

TYPE: Optional[Sequence[str | Path]] DEFAULT: None

externals

External values provided at runtime

TYPE: Optional[Dict[str, Any]] DEFAULT: None

external_sources

Mapping of external names to sources

TYPE: Optional[Dict[str, str]] DEFAULT: None

reachable_names

Optional set of reachable binding names

TYPE: Optional[Set[str]] DEFAULT: None

run_id

Optional run ID (generated if not provided)

TYPE: Optional[str] DEFAULT: None

include_payload

Whether to include config files and requirements.lock

TYPE: bool DEFAULT: True

file_origins

Optional file origins dict for creating portable bundle

TYPE: Optional[Dict[str, Any]] DEFAULT: None

entry_path

Optional entry config path (required if file_origins is provided)

TYPE: Optional[Path] DEFAULT: None

profile_paths

Optional list of resolved profile paths for bundling

TYPE: Optional[Sequence[Path]] DEFAULT: None

profile_file_origins

Optional file origins from profile includes for bundling

TYPE: Optional[Dict[str, Any]] DEFAULT: None

base_commit

Explicit base commit for patch range (e.g. replay worktree). When None, uses @{u} for upstream.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION
str | Path

Path to the snapshot directory

load_snapshot

load_snapshot(snapshot_path: str | Path) -> Dict[str, Any]

Load a snapshot from disk or GCS.

PARAMETER DESCRIPTION
snapshot_path

Path to snapshot directory or log.json file

TYPE: str | Path

RETURNS DESCRIPTION
Dict[str, Any]

Dict containing the snapshot data

build_ir_graph

build_ir_graph(compiled: Dict[str, Any], reachable_names: Optional[Set[str]] = None) -> Dict[str, Any]

Transform compiled data into a serializable IR graph.

The IR graph is a flat dictionary where: - Keys are binding names (e.g., "model", "consts/lr") - Values are node definitions with resolved kwargs and defaults

PARAMETER DESCRIPTION
compiled

Compiled configuration data from ASTCompiler

TYPE: Dict[str, Any]

reachable_names

Optional set of names to include (for sub-DAG snapshots)

TYPE: Optional[Set[str]] DEFAULT: None

RETURNS DESCRIPTION
Dict[str, Any]

Dict representing the flattened IR graph

check_introspection_warnings

check_introspection_warnings(graph: Dict[str, Any]) -> List[Dict[str, Any]]

Check graph nodes for incomplete introspection.

Returns a list of warning dicts if any providers have non-ok introspection status. Nested recipes are reported once under their containing binding.

IntrospectionInfo dataclass

IntrospectionInfo(status: IntrospectionStatus, defaults_source: str, opaque_reason: Optional[Dict[str, str]] = None)

Introspection metadata for a provider node.

to_dict

to_dict() -> Dict[str, Any]

Serialize to dictionary for JSON output.

IntrospectionStatus

Bases: str, Enum

Status of signature introspection for a provider.

OpaqueReasonCode

Bases: str, Enum

Reason codes for why introspection failed or was incomplete.


Formatter

format_source

format_source(source: str, *, filename: str | None = None, options: FormatOptions | None = None) -> str

Parse source and return the canonically-formatted rendering.

PARAMETER DESCRIPTION
source

pfig source code.

TYPE: str

filename

Optional filename used in parse-error messages.

TYPE: str | None DEFAULT: None

options

Formatter options; defaults to FormatOptions().

TYPE: FormatOptions | None DEFAULT: None

RAISES DESCRIPTION
FormatError

When the source cannot be parsed.

FormatOptions dataclass

FormatOptions(line_length: int = 100, indent: int = 4)

Knobs for the formatter. Defaults match the agreed style.

See the CLI reference for style rules and the pfig fmt command-line interface.


Data Classes

ExecutionMetadata dataclass

Metadata from pfig execution, used for snapshotting and introspection.

This dataclass captures the full execution context including compiled configuration, materialized objects, and the execution result.

ATTRIBUTE DESCRIPTION
compiled

The compiled configuration dictionary containing all resolved bindings.

TYPE: Dict[str, Any]

entrypoint_name

The resolved entrypoint binding name (e.g., "entrypoint").

TYPE: str

reachable_names

Set of binding names reachable from the entrypoint.

TYPE: Set[str]

materialized

Dictionary mapping binding names to their materialized Python objects.

TYPE: Dict[str, Any]

externals

Alias-expanded resolved runtime values for lookup. The compiled runtime_inputs/runtime_sources maps hold compact snapshot assignments.

TYPE: Dict[str, Any]

included_files

List of paths to all included .pfig files (resolved absolute paths).

TYPE: List[str]

file_origins

Dictionary mapping file paths to their IncludeResolution (for bundling).

TYPE: Dict[str, 'IncludeResolution']

result

Result of calling the entrypoint. None when returned from validate_pfig().

TYPE: Any

Example
from pfig import parse_pfig_source
from pfig.execution import validate_pfig

config = '''
from collections import OrderedDict
settings = OrderedDict(batch_size=64)
__entrypoint__ = @settings.keys
'''
ast = parse_pfig_source(config)
metadata = validate_pfig(ast)
metadata.entrypoint_name  # '__entrypoint__'
'settings' in metadata.reachable_names  # True

ProfileSpec dataclass

Profile file with an optional application prefix.

When prefix is non-empty, every override in the profile is interpreted relative to that prefix. For example, prefix=("train",) causes override output_dir = ... to apply as train/output_dir.

ValidationIssue dataclass

A single validation issue discovered during compilation or validation.

format

format(include_position: bool = True) -> str

Format the issue for display.


Helpers

entrypoint

entrypoint(fn: Callable[..., Any], /, **bound_kwargs: Any) -> Callable[[], Any]

Wrap a callable and bound kwargs into a zero-argument entrypoint.

This is a small convenience for pfig configs that want to wire arguments into a function while still satisfying pfig's expectation that __entrypoint__ is a zero-argument callable.

PARAMETER DESCRIPTION
fn

The callable to wrap.

TYPE: Callable[..., Any]

**bound_kwargs

Keyword arguments to bind to the callable.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
Callable[[], Any]

A zero-argument callable that invokes fn(**bound_kwargs).

Example

In Python:

from pfig import entrypoint

def train(run_id: str, *, seed: int) -> None:
    ...

ep = entrypoint(train, run_id="exp1", seed=42)
ep()  # calls train(run_id="exp1", seed=42)

The fn parameter is positional-only. The keyword-only pfig DSL cannot call this helper directly; expose a Python adapter instead:

def training_entrypoint(*, run_id, seed):
    return entrypoint(train, run_id=run_id, seed=seed)

Then wire training_entrypoint(run_id=@run_id, seed=@consts/seed) as the config's __entrypoint__.

entrypoint(fn, **kwargs) is a Python helper. Its fn parameter is positional-only and cannot currently be supplied directly in a .pfig call. For the DSL, expose a keyword-friendly Python factory returning a zero-argument callable; see Wiring a plain function.


Exceptions

ExecutionError

ExecutionError(message: str, provider_name: str | None = None, position: Position | None = None)

Bases: Exception

Error during provider materialization.

ValidationError

ValidationError(issues: List['ValidationIssue'])

Bases: Exception

Raised when validation fails with one or more issues.

This exception collects multiple validation issues and reports them together, allowing users to see all problems at once rather than fixing them one at a time.

ParseError

ParseError(message: str, position: Position)

Bases: Exception

LexerError

LexerError(message: str, position: Position)

Bases: Exception

FormatError

Bases: Exception

Raised when source cannot be formatted (e.g. parse failure).