API Reference

Everything documented here is importable directly from the top-level literalizer package (exceptions live in literalizer.exceptions).

Core functions

literalizer.literalize(*, source: str, input_format: InputFormat, language: Language, pre_indent_level: int = 0, include_delimiters: bool = True, variable_form: NewVariable | ExistingVariable | BothVariableForms | None = None, wrap_in_file: bool = False, ref_case: IdentifierCase | None = None, ref_values: Mapping[str, ValueInput] | None = None, bound_refs: Mapping[str, ValueInput] | None = None, ref_key: str = '$ref', collection_layout: CollectionLayout = CollectionLayout.COMPACT) LiteralizeResult

Convert a JSON, JSON5, YAML, or TOML string to a native language literal.

YAML and TOML comments are preserved in the output using the target language’s comment syntax.

Parameters:
  • source – The input string to convert.

  • input_format – The serialization format of source.

  • language – A Language instance describing how to format literals. Use one of the built-in constants (e.g. PYTHON, GO) or provide your own. Languages whose wrap_in_file introduces a named scope (the wrapping class in Java, the program in Fortran, the -module in Erlang) carry that name as a constructor argument (Java(module_name="Foo")); languages whose wrappers do not introduce a named scope take no such argument.

  • pre_indent_level – Number of indent steps to prepend to every output line. For example, 2 with a 4-space indent produces an 8-space margin. Defaults to 0.

  • include_delimiters – If True, include the collection delimiters ([] for arrays, {} for dicts).

  • variable_form – Controls how the output is wrapped in a variable. Pass NewVariable to use format_variable_declaration (e.g. const x = in JavaScript), ExistingVariable to use format_variable_assignment (e.g. x =), or BothVariableForms to produce both a declaration and an assignment combined in one output (requires wrap_in_file). None (default) means no variable wrapping.

  • wrap_in_file – If True, assemble code as a complete, valid source file using the language’s wrap_in_file method and prepend preamble. When set, preamble and body_preamble on the result are empty tuples (their content has been folded into code).

  • ref_case – Optional IdentifierCase controlling how ref identifiers are cased in the rendered output. {ref_key: "name"} markers anywhere in the data are rendered as bare identifiers using the language’s format_call_ref_identifier hook. When None (default), ref names are emitted verbatim. When set, the identifier name is converted to ref_case first.

  • ref_values – Optional mapping from ref identifier to the value declared elsewhere for that ref. Some languages render a ref differently depending on the type behind it (V emits name for primitive scalars but name.clone() for arrays and maps); supplying ref_values lets those languages pick the right form. When omitted, a ref’s type is unknown and languages fall back to their type-agnostic default. Keys should match the identifiers used in source before any ref_case conversion.

  • bound_refs – Optional mapping from ref identifier to the value that ref should be bound to. Unlike ref_values (which only feeds type knowledge to the ref site, leaving the ref as a free external identifier), each name in bound_refs additionally has a binding emitted for it, in bound_refs iteration order, so a single literalize call with wrap_in_file=True produces a complete, valid file with per-language declaration sequencing (Nix nested let, Fortran two-phase declarations, and so on). Supply bound_refs ordered by each ref’s first use in source (and limited to refs that appear there) so every binding precedes its first use and no unused binding is emitted. Binding emission only happens when wrap_in_file is True and variable_form is a NewVariable or ExistingVariable (a binding the refs can precede); otherwise bound_refs degrades to type information only, exactly like ref_values, and the refs stay free identifiers. Entries also act as ref_values for their names, so a name need not be repeated in both mappings. Keys should match the identifiers used in source before any ref_case conversion. Defaults to None (no bindings emitted; behavior is byte-identical to omitting this argument).

  • ref_key – The dict key used to identify variable-reference markers in the input data. A single-key dict whose key equals ref_key and whose value is a string is treated as a ref marker. Defaults to "$ref".

  • collection_layout – Controls layout for collections nested inside other collections. CollectionLayout.COMPACT preserves the existing one-line nested rendering, while CollectionLayout.MULTILINE expands non-empty nested collections with one element per line.

Raises:
  • JSONParseError – If input_format is JSON and source is not valid JSON.

  • JSON5ParseError – If input_format is JSON5 and source is not valid JSON5.

  • YAMLParseError – If input_format is YAML and source is not valid YAML.

  • TOMLParseError – If input_format is TOML and source is not valid TOML.

  • HeterogeneousCollectionError – If the data contains collections whose shape cannot be represented in the target language (e.g. heterogeneous scalar types in a language that requires homogeneous collections).

  • ValueError – If variable_form is BothVariableForms and wrap_in_file is False, or if the language’s declaration_style does not support redefinition.

  • UnsupportedIdentifierCaseError – If ref_case is not in supported_ref_cases for the target language.

  • VariableNameNotSupportedError – If variable_form is supplied but the target language sets supports_variable_names to False.

  • WrapInFileWithoutVariableNotSupportedError – If wrap_in_file is True and variable_form is None but the target language sets supports_no_variable_wrap_in_file to False (i.e. it cannot represent a bare value at file-statement scope).

literalizer.literalize_call(*, source: str, input_format: InputFormat, language: Language, target_function: str, parameter_names: Sequence[str], call_transform: Callable[[CallContext], str] | None = None, zip_source: str | None = None, zip_input_format: InputFormat | None = None, comment_source: Sequence[str] | None = None, per_element: bool = True, wrap_in_file: bool = False, ref_case: IdentifierCase | None = None, consumable_refs: frozenset[str] = frozenset({}), ref_values: Mapping[str, ValueInput] | None = None, bound_refs: Mapping[str, ValueInput] | None = None, ref_key: str = '$ref', collection_layout: CollectionLayout = CollectionLayout.COMPACT, variable_form: NewVariable | ExistingVariable | BothVariableForms | None = None) LiteralizeResult

Convert data to function call expressions in the target language.

Each top-level list element (when per_element is True) becomes a separate function call with arguments formatted according to the language’s call_style_config.

Parameters:
  • source – The input string to convert.

  • input_format – The serialization format of source.

  • language – A Language instance describing how to format literals.

  • target_function – The function expression to call (e.g. "throttler.should_send_notification").

  • parameter_names – Parameter names, positionally mapped to each element in each row. For PositionalCallStyle languages these are unused in the output but still determine how many values to expect per row.

  • call_transform – Optional callable transforming each generated call. Invoked once per call as call_transform(context) with a CallContext and returns the transformed string (e.g. lambda ctx: f"print({ctx.call})"). The context also exposes the call’s zero-based index, its input row, and the paired zipped literal, so a transform can render data from a parallel sequence beside each call. Only supported for languages whose call form is an expression that can be wrapped (positional, keyword, or object call style); prefix/postfix/command-style languages reject it with UnsupportedCallShapeError.

  • zip_source – Optional companion source whose parsed top-level elements pair positionally with the generated calls. It is parsed with the same parser as source (so YAML !!omap, datetime/bytes coercion, JSON5, TOML, … behave identically by construction), each paired value is rendered to a language-native literal (via the same machinery as literalize()) and exposed on CallContext.zipped for the matching call, enabling patterns like printing an expected value beside each call’s actual return value. When per_element is True it must parse to a list whose top-level elements pair element-by-element with the calls (a non-list raises PerElementNotListError); otherwise the whole parsed value pairs with the single call. A length mismatch raises ZipValuesLengthMismatchError. Requires zip_input_format (supplying zip_source without it raises ZipSourceWithoutInputFormatError) and call_transform (the values are only reachable through it; supplying zip_source without one raises ZipValuesWithoutCallTransformError).

  • zip_input_format – The serialization format of zip_source. Required whenever zip_source is supplied and ignored otherwise.

  • comment_source – Optional sequence of trailing source-code comments, one per generated call, paired positionally. Each non-empty entry is emitted as a line comment after the statement terminator on the call’s last line, using the language’s comment_config leader (#, //, --, …); languages with no line comment fall back to that language’s block-comment form (/* ... */), which is valid on a single line. Because the comment is applied to the fully terminated statement, a line-comment leader never swallows the terminator (a problem a call_transform cannot avoid, since it only sees the pre-terminator call expression). An empty entry emits no comment. Unlike zip_source this is a plain sequence (not a parsed source) and needs neither a call_transform nor an input format. The entry count must equal the number of generated calls – one per top-level element when per_element is True, otherwise one for the single call – or CommentSourceLengthMismatchError is raised; an entry containing a newline raises CommentSourceMultilineError. A trailing comment is only safe where each generated call is a self-contained line; languages that assemble the call sequence into a single clause/list/expression (so a separator, terminator or closer follows the call on the same line, which a line comment would swallow) reject a non-empty comment_source with UnsupportedCallShapeError. The supported set is exactly the languages whose supports_standalone_comments_in_wrapped_calls is True.

  • per_element – If True (default), each top-level list element becomes a separate call (an element that is itself an empty list yields a zero-argument call). If False, the whole literalized value is passed as a single argument. A variable_form binding requires exactly one call, so it is valid with per_element=False (always one call) or with per_element=True over a single-element source; the zero-argument constructor p2 = Playlist() is produced by the latter with a [[]] source.

  • wrap_in_file – If True, assemble code as a complete, self-contained source file using the language’s wrap_in_file method and prepend preamble. A no-op stub for target_function is also injected so the generated file does not reference an undefined name; when a call_transform is supplied the wrapper name it introduces is not stubbed — callers that transform calls are responsible for providing that definition themselves. When set, preamble and body_preamble on the result are empty tuples (their content has been folded into code).

  • ref_case – Optional IdentifierCase controlling how ref identifiers are cased in the rendered output. When None (default) ref names are emitted verbatim. When set, each ref identifier is normalized to snake_case and then converted to the requested case via pyhumps, so the same source can drive idiomatic identifiers across multiple languages. When language’s supported_ref_cases does not expose the requested case, UnsupportedIdentifierCaseError is raised.

  • consumable_refs – Names of ref identifiers this call owns and may move from. Refs in this set may be rendered with a consuming form (e.g. C++ std::move) when they appear in exactly one call argument; refs used by more than one call – or omitted from this set – are emitted as the bare identifier so subsequent uses of the variable remain valid. Names should match the identifiers used in source before any ref_case conversion. Defaults to an empty set (no refs are consumed).

  • ref_values – Optional mapping from ref identifier to the source value declared elsewhere. When supplied, values for refs used in source are included in data-driven preamble inference, so languages with generated body types (for example Haskell’s data Val = ...) declare constructors for types reachable only through refs. Missing ref names keep the historical behavior: their markers are omitted from preamble inference. Keys should match the identifiers used in source before any ref_case conversion.

  • bound_refs – Optional mapping from ref identifier to the source value that ref should be declared with. The recommended way to render a complete, self-contained file that declares each ref and then calls the target with it: literalize exposes the same argument for the declaration-only case, and this is its call-side counterpart. Each entry is emitted as a NewVariable declaration (cased via ref_case) in bound_refs iteration order ahead of the calls, the value is folded into preamble inference exactly like ref_values (so a name need not be repeated in both mappings; an explicit ref_values entry for the same name wins), and the declarations, calls, and a no-op stub for target_function are wrapped into one file via wrap_calls_with_declarations() with a single reconciled preamble. Declaration emission only happens when wrap_in_file is True; otherwise bound_refs degrades to type information only, exactly like ref_values, and the refs stay free identifiers. Every name should appear as a $ref marker in source (a ref that is declared but never referenced is folded into neither the call nor its preamble inference and so may leave the declaration’s data-dependent preamble entries uncovered, besides being an unused binding); this mirrors literalize’s bound_refs contract. Incompatible with variable_form (which binds the call result): the two are rejected together with UnsupportedCallShapeError because the declaration-composition path cannot apply a language’s call-result binding file scaffold. Keys should match the identifiers used in source before any ref_case conversion. Defaults to None (no bindings emitted; behavior is byte-identical to omitting this argument).

  • ref_key – The dict key used to identify variable-reference markers in the input data. A single-key dict whose key equals ref_key and whose value is a string is treated as a ref marker. Defaults to "$ref".

  • collection_layout – Controls layout for collections nested inside call arguments. CollectionLayout.COMPACT preserves the existing one-line nested rendering, while CollectionLayout.MULTILINE expands non-empty nested collections with one element per line.

  • variable_form – When supplied, wrap the call expression in a variable binding using the language’s format_variable_declaration / format_variable_assignment hook (the same machinery used by literalize()). Pass NewVariable for an idiomatic declaration (let p2 = Playlist::new();, const p2 = new Playlist();, p2 = Playlist()) or ExistingVariable for an assignment to an existing name. BothVariableForms is rejected with UnsupportedCallShapeError because emitting both a declaration and an assignment would invoke the target function twice. Mutability and inference are controlled by the per-language declaration_style and Modifiers enums on the supplied Language instance, not by extra arguments here. A single name can bind only one call result, so the input must produce exactly one call: per_element=False always does, and per_element=True does when the source has exactly one top-level element (a single-element [[]] source is how the zero-argument constructor p2 = Playlist() is reached). Zero calls (an empty per_element source) or more than one call are rejected with UnsupportedCallShapeError, as are languages whose call form is not an expression (call_returns_expression=False).

Note

When composing the output of this function with literalize() — for example, declaring a variable with literalize() and then referencing it via a ref marker in the call — the two halves each compute preamble and body_preamble independently from the data they see. Concatenating the results into a single file can produce duplicate import lines or duplicate type declarations, which strict compilers (Haskell, D, …) reject and a linter (ruff, pylint, …) flags. Pass the ref values through bound_refs (with wrap_in_file=True) instead and this function renders the declarations and the calls into one coherent file with a single reconciled preamble. The “Composing declarations and calls” section of Rendering function calls shows a worked example.

Result type

class literalizer.LiteralizeResult(declaration_code: str, preamble: tuple[str, ...], body_preamble: tuple[str, ...], pre_declaration_comments: tuple[str, ...] = (), types_present: frozenset[type] = frozenset({}), contains_standalone_comments: bool = False, source_data: Value = None, sections: tuple[FileSection, ...] = ())

Result of converting data to a native language literal.

property bare_code: str

The literal text without body_preamble prepended.

Identical to code when body_preamble is empty. pre_declaration_comments are preserved.

body_preamble: tuple[str, ...]

Type-definition lines (e.g. F#’s type Val = , Haskell’s data Val = and typeclass instances) that are prepended to code. Empty when none are needed.

Use bare_code to obtain the literal text without these lines.

property code: str

The formatted literal text.

When a language defines scalar_body_preamble entries (e.g. Haskell typeclass instances), those lines are prepended to the code so they appear in the correct structural position.

contains_standalone_comments: bool = False

Whether the rendered source carried standalone comments (lines whose only content is a comment, distinct from inline trailing comments). Set when literalize_call parses YAML input that contains top-level before-element or trailing comments. Callers that wrap the result via Language.wrap_calls_with_declarations() can consult this together with Language.supports_standalone_comments_in_wrapped_calls to decide whether wrapping is safe.

declaration_code: str

The variable declaration or assignment text, without any body_preamble or pre_declaration_comments lines.

Use code for the full formatted text including all prefix lines.

pre_declaration_comments: tuple[str, ...] = ()

Already-formatted comment lines that appear between body_preamble and the variable declaration/assignment in code. These come from scalar before-comments when the language does not support them inline.

Included in bare_code but excluded from declaration_code.

preamble: tuple[str, ...]

Lines (imports, package declarations, etc.) that must precede the generated code. Empty when none are needed.

sections: tuple[FileSection, ...] = ()

For multi-section languages, the rendered output split into its file regions; empty for the single-section common case.

A few languages cannot express a value as one drop-in fragment: their output spans more than one region of a source file that a wrapping template must place separately. COBOL under json_type=CJSON is the current example, emitting a WORKING-STORAGE region of declarations and a PROCEDURE region of statements.

Only populated when wrap_in_file=False (with wrap_in_file=True the language has already composed the regions into a complete file). When non-empty, compose these FileSection regions into your own template; code / declaration_code then hold an opaque marker-bracketed payload (the form the language’s wrappers consume), not usable source. Empty for almost every language; use code then.

source_data: Value = None

The parsed source value the literal was rendered from. Most callers do not need it. Callers that combine multiple literalize results and re-invoke Language.compute_body_preamble to derive a single body preamble surface this so the second call can inspect the actual values (e.g. datetime microsecond precision) rather than a placeholder.

types_present: frozenset[type] = frozenset({})

The set of Python types observed in the source data (e.g. int, str, list, dict). Callers that combine multiple literalize results (for example, a test harness that pairs $ref declarations with a downstream call) can union these and re-invoke Language.compute_body_preamble to derive a single body preamble that covers every type referenced across the combined output.

class literalizer.FileSection(*, name: str, content: str)

One named region of a multi-section language’s rendered output.

Most languages render a value as a single fragment that a caller can drop straight into a program template (the way the C, C++, Haskell and Zig round-trip helpers do). A few cannot: their output spans more than one region of a source file that a wrapping template must place separately. COBOL under json_type=CJSON is the current example – it produces WORKING-STORAGE declarations and PROCEDURE DIVISION statements that live in different divisions.

For such languages sections exposes the regions as a tuple of these objects, so a caller can compose each one into the right place in its own template without parsing any language-internal marker. Single-section languages leave that attribute empty.

content: str

The region’s text, with no marker lines and no enclosing program boilerplate.

name: str

A stable label identifying the region within its language (for COBOL json_type=CJSON, "WORKING-STORAGE" or "PROCEDURE").

Variable forms

The bound_refs argument to literalize() and literalize_call() describes each referenced name as one of these forms.

class literalizer.NewVariable(name: str, modifiers: frozenset[Enum] = frozenset({}))

Wrap output in a new variable declaration.

modifiers: frozenset[Enum] = frozenset({})

Declaration modifiers to apply. Each language exposes its own modifier enum as Language.Modifiers (e.g. Java.Modifiers.FINAL, CSharp.Modifiers.READONLY, Cpp.Modifiers.STATIC). Values that are not members of the target language’s Modifiers enum are silently ignored.

name: str
class literalizer.ExistingVariable(name: str)

Wrap output in an assignment to an existing variable.

name: str
class literalizer.BothVariableForms(name: str, modifiers: frozenset[Enum] = frozenset({}))

Produce both a declaration and an assignment, combined.

Requires wrap_in_file=True on literalize().

modifiers: frozenset[Enum] = frozenset({})

Declaration modifiers applied to the declaration half. See NewVariable.modifiers.

name: str
literalizer.VariableForm = literalizer._literalize.NewVariable | literalizer._literalize.ExistingVariable | literalizer._literalize.BothVariableForms

Represent a PEP 604 union type

E.g. for int | str

class literalizer.ModifierCombination(name: str, modifiers: frozenset[Enum])

A named combination of declaration modifiers for a language.

Languages that support declaration modifiers (e.g. Java public static final, C# public static readonly, C++ static const) expose their canonical multi-modifier combinations via LanguageCls.modifier_combinations.

modifiers: frozenset[Enum]

The set of modifier enum members that make up this combination.

name: str

Identifier for this combination, used in generated code.

Identifier cases

class literalizer.IdentifierCase(*values)

A naming convention for a single identifier.

Passed to literalize_call() via ref_case to convert {"$ref": "name"} markers to the target language’s idiomatic case at render time. Each Language exposes the subset it understands via its nested IdentifierCases enum.

CAMEL = 'camel'

camelCase — e.g. userObj.

KEBAB = 'kebab'

kebab-case — e.g. user-obj.

PASCAL = 'pascal'

PascalCase — e.g. UserObj.

SNAKE = 'snake'

snake_case — e.g. user_obj.

UPPER_SNAKE = 'upper_snake'

UPPER_SNAKE_CASE — e.g. USER_OBJ.

convert(*, name: str) str

Return name converted to this case.

Normalizes any input convention to snake_case first so the conversion is deterministic even when the source identifier does not follow the recommended snake_case authoring convention. Acronyms are lost in normalization (HTTPRequest becomes http_request and then HttpRequest), so passing snake_case input when exact-round-trip matters is recommended.

literalizer.ALL_REF_CASES = frozenset({IdentifierCase.CAMEL, IdentifierCase.KEBAB, IdentifierCase.PASCAL, IdentifierCase.SNAKE, IdentifierCase.UPPER_SNAKE})

Build an immutable unordered collection of unique elements.

literalizer.NON_KEBAB_REF_CASES = frozenset({IdentifierCase.CAMEL, IdentifierCase.PASCAL, IdentifierCase.SNAKE, IdentifierCase.UPPER_SNAKE})

Build an immutable unordered collection of unique elements.

Function calls

class literalizer.CallContext(call: str, index: int, row: Sequence[Value], zipped: str | None)

Per-row context passed to a literalize_call() call_transform.

A call_transform is invoked once per generated call as call_transform(context) and returns the transformed call string. The context carries the call’s positional identity so a transform can pair it with data from a parallel source (see literalize_call()’s zip_source).

call: str

The rendered language-native call expression (e.g. catalog.lookup("Dune", 1965)).

index: int

Zero-based position of this call among the generated calls.

row: Sequence[Value]

The input values for this row, in source order. For per_element=True this is the top-level element at position index, as its argument values; for per_element=False it is the whole parsed value wrapped in a single-element sequence.

zipped: str | None

The zip_source element paired with this call, rendered as a language-native literal, or None when no zip_source was supplied.

A language renders a call using one of these call styles.

literalizer.CallStyle = literalizer._language.PositionalCallStyle | literalizer._language.KeywordCallStyle | literalizer._language.ObjectCallStyle | literalizer._language.PostfixCallStyle | literalizer._language.PrefixCallStyle | literalizer._language.CommandCallStyle

Represent a PEP 604 union type

E.g. for int | str

class literalizer.PositionalCallStyle(arg_separator: str, parenthesize_each_arg: bool)

Positional arguments only: func(value1, value2).

arg_separator: str
parenthesize_each_arg: bool
class literalizer.KeywordCallStyle(separator: str)

Named arguments: func(name=value).

separator is the string placed between the parameter name and its value (e.g. "=" for Python, ": " for Ruby).

separator: str
class literalizer.ObjectCallStyle(separator: str)

Arguments wrapped in an object literal: func({ name: value }).

separator is the string placed between the parameter name and its value inside the object literal (e.g. ": " for JavaScript).

separator: str
class literalizer.PrefixCallStyle(arg_separator: str, keyword_prefix: str)

S-expression-style calls: (func value1 value2).

Used by Lisp-family languages (Racket, Scheme, Common Lisp, Clojure) where the function and its arguments are wrapped together in one pair of parentheses. arg_separator is the string between arguments (typically a single space).

Arguments are emitted as {keyword_prefix}{name}{arg_separator}{value} pairs (e.g. Racket’s #:user_id "u").

arg_separator: str
keyword_prefix: str
class literalizer.PostfixCallStyle(arg_separator: str)

Postfix (stack) calls: value1 value2 func.

Used by stack-based languages like Forth where arguments are pushed onto the stack before the word is invoked. arg_separator is the string placed between arguments.

arg_separator: str
class literalizer.CommandCallStyle(arg_separator: str)

Shell-command-style calls: func value1 value2.

Used by shell languages (Bash, POSIX sh) and Tcl where the function name is followed by space-separated positional arguments with no surrounding parentheses. arg_separator is the string between the target and each argument (typically a single space).

call_transform is not supported for this style (see literalize_call()).

arg_separator: str
class literalizer.StubReturn(*values)

Whether a generated call stub returns a value or nothing.

Passed to Language.format_call_stub and Language.format_call_preamble_stub to control the return type of the no-op target-function stub emitted when a call is wrapped in a self-contained file.

VALUE = 'value'

The call result is consumed (passed to a call_transform or bound to a variable), so the stub returns a value.

VOID = 'void'

The call result is discarded, so the stub returns nothing.

Input formats

class literalizer.InputFormat(*values)

Supported input serialization formats.

JSON = 1
JSON5 = 2
TOML = 4
YAML = 3

Exceptions

Exceptions raised by literalizer.

exception literalizer.exceptions.CallArgNotSupportedError(*, language_name: str, reason: str)

Raised when a call argument value cannot be expressed as a positional argument in the target language’s call syntax.

Used by languages whose call syntax does not accept compound literals as arguments, e.g. Bash, where cmd (1 2 3) parses as a nested (...) child-process invocation rather than an inline array value.

To resolve, bind the value to a name first, or target a language that accepts the argument inline.

exception literalizer.exceptions.CallsNotSupportedByLanguageError(*, language_name: str)

Raised when the target language itself has no function call syntax (e.g. pure data/markup formats like YAML, TOML, JSON5, Norg).

To resolve, use literalize() instead, or target a programming language.

exception literalizer.exceptions.CallsNotSupportedByToolError(*, language_name: str)

Raised when literalizer has not yet implemented function call rendering for the target language, even though the language itself has function call syntax.

To resolve, target a language whose call rendering is implemented.

exception literalizer.exceptions.CommentSourceLengthMismatchError(*, call_count: int, comment_count: int)

Raised when literalize_call is given a comment_source whose entry count differs from the number of generated calls.

Each comment is paired positionally with one call, so the two sequences must be the same length.

To resolve, provide one comment per generated call.

exception literalizer.exceptions.CommentSourceMultilineError(*, index: int)

Raised when a comment_source entry contains a newline.

A trailing comment is emitted on the statement’s last line; a newline would push the remainder onto a line with no comment leader and, in languages whose line comment runs to end of line, produce invalid source. Comments must be single-line.

To resolve, remove the newline, keeping each comment on one line.

exception literalizer.exceptions.DottedCallTargetNotSupportedError(*, language_name: str, target_function: str)

Raised when literalize_call is given a dotted target_function but the target language does not support dotted call expressions.

To resolve, use a target name without dots, or target a language with dotted calls.

exception literalizer.exceptions.HeterogeneousCollectionError

Base class for errors raised when data is incompatible with the target language’s collection-shape constraints.

To resolve, pick a non-default heterogeneous_strategy (see Heterogeneous strategies) or render the value through a json_type (see JSON value types); catch this base class to skip any heterogeneous input a strict-typed language cannot hold.

exception literalizer.exceptions.HeterogeneousScalarCollectionError

Raised when a collection contains scalars of multiple types and the target language requires homogeneous scalar collections.

For example, [1, "two", 3.0] for a language that needs a single element type. To resolve, set heterogeneous_strategy to TAGGED_ENUM (or the language’s equivalent) to wrap each scalar, or to TUPLE for a fixed-length array.

exception literalizer.exceptions.HeterogeneousSetError

Raised when a set contains scalars of multiple types and the target language requires homogeneous set elements.

To resolve, use one scalar type, or a richer heterogeneous_strategy.

exception literalizer.exceptions.HeterogeneousSiblingListsError

Raised when sibling sub-lists contain scalars that, combined, span multiple types and the target language requires homogeneous scalar collections.

To resolve, use a TAGGED_ENUM strategy, or render the value through a json_type.

exception literalizer.exceptions.IncompatibleFormatsError

Raised when a combination of format options produces invalid code.

For example, Rust CONST and STATIC declaration styles require constant-expression initializers, but the VEC sequence format produces vec![…] which is not a constant expression.

To resolve, change one of the conflicting options so they agree.

exception literalizer.exceptions.InvalidDictKeyError

Raised when a dict key cannot be represented in the target language.

This includes empty-string keys and keys containing characters that the language’s label syntax does not support (e.g. control characters in Dhall backtick-quoted labels). To resolve, remove or rename the offending key.

exception literalizer.exceptions.InvalidRecordNameError

Raised when record_struct_name_prefix or a value in record_shape_names is not a valid PascalCase identifier, collides with a reserved keyword of the target language, collides with heterogeneous_value_enum_name, or duplicates another mapped struct name.

To resolve, use distinct, valid PascalCase names that avoid reserved keywords.

exception literalizer.exceptions.JSON5ParseError

Raised when a JSON5 string cannot be parsed.

To resolve, fix the JSON5 syntax, or choose the matching input_format.

exception literalizer.exceptions.JSONParseError

Raised when a JSON string cannot be parsed.

To resolve, fix the JSON syntax, or pass the correct input_format if the data is really JSON5, YAML, or TOML.

exception literalizer.exceptions.MixedDictKeysError

Raised when a dict has keys spanning multiple type families and the target language requires homogeneous dict keys.

To resolve, use a single key type, or render through a json_type.

exception literalizer.exceptions.MixedDictShapesError

Raised when a list contains dicts with different key sets and the target language requires uniform record shapes (e.g. Dhall).

To resolve, make every dict share the same keys, or use a json_type.

exception literalizer.exceptions.MixedDictValuesError

Raised when a dict has values spanning multiple type families and the target language requires homogeneous dict values.

To resolve, use the RECORD strategy if the dict is conceptually a record, or a json_type for arbitrary mappings.

exception literalizer.exceptions.MixedListValuesError

Raised when a list has elements spanning multiple type families and the target language requires homogeneous list elements.

To resolve, use a richer heterogeneous_strategy or a json_type.

exception literalizer.exceptions.NullInCollectionError

Raised when a collection contains null elements and the chosen format does not support them (e.g. Java’s List.of()).

To resolve, remove the nulls, or select a collection format that admits them.

exception literalizer.exceptions.ParameterCountMismatchError(*, expected: int, got: int)

Raised when the number of parameter_names does not match the number of argument values in a function-call row.

To resolve, make parameter_names the same length as each row of values.

exception literalizer.exceptions.ParseError

Raised when input cannot be parsed into a data structure.

Base class for every input-parsing failure; catch it to handle any malformed input uniformly. To resolve, validate the source against its declared input_format.

exception literalizer.exceptions.PerElementNotListError

Raised when per_element=True but the parsed data is not a list.

To resolve, pass a list, or drop per_element.

exception literalizer.exceptions.TOMLParseError

Raised when a TOML string cannot be parsed.

To resolve, fix the TOML syntax, or choose the matching input_format.

exception literalizer.exceptions.TupleArityNotRepresentableError(*, arity: int)

Raised when the TUPLE heterogeneous strategy meets a tuple-eligible heterogeneous scalar array whose length the target language has no native fixed-size tuple for.

Kotlin only has Pair (two elements) and Triple (three elements); an array of any other length cannot be represented as a typed tuple without losing the per-position types, so literalize raises rather than falling back to a homogeneous list (which would re-trip the heterogeneity checks the strategy exists to satisfy). Subclasses HeterogeneousCollectionError so the same callers that already skip a heterogeneous input the language cannot represent also skip this one.

To resolve, shorten the array to a length the language supports, choose a language without the tuple-length cap (Rust, Scala), or switch to a TAGGED_ENUM strategy.

exception literalizer.exceptions.UnrepresentableEmptyDictError

Raised when an empty dict is passed to a target language whose runtime cannot distinguish an empty mapping from an empty sequence.

Lua, PHP, and R encode both empty arrays and empty objects with the same surface syntax ({}, [], and list() respectively), so the JSON encoders in their ecosystems serialize an empty mapping as []. The literalizer refuses to emit a literal that cannot round-trip rather than silently lose the mapping/sequence distinction.

To resolve, drop the empty mapping, or target a language that distinguishes the two.

exception literalizer.exceptions.UnrepresentableInputError

Raised when an input value cannot be represented in the target language.

Used as the centralized error for shape-level rejections at the formatting boundary, e.g. when a dict carries a non-string key for a language whose surface syntax only admits string-typed keys. To resolve, adjust the data to a representable shape, or pick a language that supports it.

exception literalizer.exceptions.UnrepresentableIntegerError

Raised when an integer value exceeds the range the target language can represent natively.

Used by languages whose fixed-width integer types cannot hold values outside the signed 64-bit range (e.g. Fortran default integer, Cobol PIC S9(18), PureScript Int) when no external arbitrary-precision integer library is assumed to be available.

To resolve, keep integers within range, or target a language with wider or arbitrary-precision integers.

exception literalizer.exceptions.UnrepresentableSpecialFloatError

Raised when a non-finite float (inf, -inf, or nan) is passed to a target language whose runtime cannot produce IEEE 754 special float values.

Used by Gleam on the Erlang target, which has no expression that evaluates to a non-finite float.

To resolve, replace the non-finite floats with finite values, or pick another language.

exception literalizer.exceptions.UnsupportedCallShapeError(*, language_name: str, reason: str)

Raised when literalize_call is given a call shape the target language cannot represent.

Distinct from CallArgNotSupportedError (which concerns individual argument values): this covers structural properties of the call itself, e.g. zero-parameter calls in languages whose syntax requires at least one operand.

To resolve, adjust the call shape, or target a language that supports it.

exception literalizer.exceptions.UnsupportedIdentifierCaseError(*, language_name: str, case_name: str)

Raised when literalize or literalize_call is passed a ref_case that is not in the target language’s supported_ref_cases – i.e. one that would not produce a syntactically legal identifier in the target language.

To resolve, choose a ref_case from the language’s supported_ref_cases.

exception literalizer.exceptions.VariableNameNotSupportedError(*, language_name: str, variable_name: str)

Raised when literalize is given a variable_form but the target language does not support variable-name wrapping.

To resolve, omit variable_form for that language, or target one that supports it.

exception literalizer.exceptions.WrapCombinedInFileNotSupportedError

Raised when a language does not support wrap_combined_in_file.

Languages that raise this error do not support BothVariableForms; literalize() rejects that form before reaching wrap_combined_in_file, but each language implementation still raises this typed exception as a safety net.

To resolve, use a single variable form, or target a language that supports the combined form.

exception literalizer.exceptions.WrapInFileWithoutVariableNotSupportedError(*, language_name: str)

Raised when literalize is called with wrap_in_file=True and variable_form=None for a target language that cannot represent a bare value at file-statement scope.

Most strict-typed compiled languages (Rust, C, C++, Haskell, Swift, OCaml, Ada, D, Dart, C#, Elm, Mojo, Nim, Objective-C, Odin, SML, V, Zig, etc.) require every top-level item to be a declaration; a bare expression at file scope is a syntax error. Such languages opt out of the shape by setting supports_no_variable_wrap_in_file to False, and literalize rejects the combination at the boundary instead of silently emitting invalid code.

To resolve, supply a variable_form so the value becomes a top-level declaration.

exception literalizer.exceptions.YAMLParseError

Raised when a YAML string cannot be parsed.

To resolve, fix the YAML syntax, or choose the matching input_format.

exception literalizer.exceptions.ZipSourceWithoutInputFormatError

Raised when literalize_call is given a zip_source but no zip_input_format describing how to parse it.

The companion source can only be parsed once its serialization format is known, so the two arguments must be supplied together.

To resolve, pass zip_input_format alongside zip_source.

exception literalizer.exceptions.ZipValuesLengthMismatchError(*, call_count: int, zip_count: int)

Raised when literalize_call is given a zip_source whose parsed top-level elements differ in number from the generated calls.

To resolve, make zip_source hold one element per generated call.

exception literalizer.exceptions.ZipValuesWithoutCallTransformError

Raised when literalize_call is given a zip_source but no call_transform to consume the paired values.

The paired values are only reachable through zipped, so supplying them without a transform would silently discard them.

To resolve, supply a call_transform that reads zipped, or drop zip_source.