API Reference

This page documents the complete public API of fluent_codegen.codegen.

Top-level containers

class fluent_codegen.codegen.Module(reserve_builtins=True)[source]

Bases: Block, CodeGenAst

Top-level module block with its own Scope pre-loaded with builtins.

Parameters:

reserve_builtins (bool)

as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

Module

as_python_source()[source]

Return the Python source code for this AST list.

Return type:

str

property enames: Enames[source]

Provides access to scope names as E-objects

e.g. Module().enames.str for the str Name that is registered as a builtin.

class fluent_codegen.codegen.Block(scope, parent_block=None)[source]

Bases: CodeGenAstList

An ordered sequence of statements sharing a common Scope.

Parameters:
as_ast_list(allow_empty=True, *, include_comments=False)[source]
Parameters:
  • allow_empty (bool)

  • include_comments (bool)

Return type:

list[stmt]

add_comment(text, *, wrap=None)[source]

Add a # text comment line at the current position in the block.

If wrap is given as an integer, long lines are wrapped at word boundaries so that no comment line exceeds wrap characters (including the # prefix and space).

Parameters:
  • text (str)

  • wrap (int | None)

Return type:

None

add_statement(statement)[source]

Append a statement, block, or bare expression to this block.

Parameters:

statement (Statement | Block | ExpressionLike)

Return type:

None

create_import(module, as_=None)[source]

Create an import statement, reserve the resulting name, and add it to this block.

Parameters:
  • module (str)

  • as_ (str | None)

Return type:

tuple[Import, Name]

create_import_from(*, from_, import_, as_=None)[source]

Create a from ... import statement, reserve the resulting name, and add it to this block.

Parameters:
Return type:

tuple[ImportFrom, Name]

create_assignment(target, value, *, type_hint=None, allow_multiple=False)[source]

Adds an assigment of the form:

x = value

or more complex like:

x[0] = value x, y = value

Parameters:
  • target (str | Target)

  • value (ExpressionLike)

  • type_hint (ExpressionLike | None)

  • allow_multiple (bool)

assign(target: str, value: ExpressionLike, *, type_hint: ExpressionLike | None = None) Name[source]
assign(target: tuple[str, ...], value: ExpressionLike) tuple[Name, ...]

Shortcut that reserves names and creates an assignment in one step.

When target is a single str, reserves the name and assigns to it, returning the new Name:

result = block.assign("x", some_expr)
# equivalent to:
#   x = scope.create_name("x")
#   block.create_assignment(x, some_expr)

When target is a tuple of str, reserves each name and creates a tuple-unpacking assignment, returning a tuple of Name objects:

a, b = block.assign(("a", "b"), some_pair_expr)
# equivalent to:
#   a = scope.create_name("a")
#   b = scope.create_name("b")
#   block.create_assignment((a, b), some_pair_expr)
Parameters:
  • target (str | tuple[str, ...])

  • value (ExpressionLike)

  • type_hint (ExpressionLike | None)

Return type:

Name | tuple[Name, …]

aug_assign(target, op, value, /)[source]

Add an augmented assignment statement to this block.

Usage:

x = block.assign("x", auto(0))
block.aug_assign(x, "+=", auto(1))   # x += 1

target must be a Name, Attr, or Subscript (tuples are not valid Python augmented-assignment targets).

op is one of the Python augmented-assignment operator strings: "+=" "-=" "*=" "/=" "//=" "%=" "**=" "@=" "<<=" ">>=" "|=" "&=" "^=".

Parameters:
  • target (AugAssignTarget)

  • op (AugOp)

  • value (ExpressionLike)

Return type:

None

create_annotation(name, annotation)[source]

Adds a bare type annotation of the form:

x: int

Reserves the name and adds the annotation statement to the block.

Parameters:
  • name (str)

  • annotation (ExpressionLike)

Return type:

Name

create_field(name, annotation, *, default=None)[source]

Create a typed field, typically used in dataclass bodies.

If default is provided, creates an annotated assignment:

x: int = 0

Otherwise, creates a bare annotation:

x: int
Parameters:
  • name (str)

  • annotation (ExpressionLike)

  • default (ExpressionLike | None)

Return type:

Name

create_function(name, args, decorators=None, return_type=None)[source]

Reserve a name for a function, create the Function and add the function statement to the block.

Parameters:
Return type:

tuple[Function, Name]

create_class(name, bases=None, decorators=None)[source]

Reserve a name for a class, create the Class and add the class statement to the block.

Parameters:
  • name (str)

  • bases (Sequence[ExpressionLike] | None)

  • decorators (Sequence[ExpressionLike] | None)

Return type:

tuple[Class, Name]

create_return(value)[source]

Add a return statement to this block.

Parameters:

value (ExpressionLike)

Return type:

None

create_break()[source]

Add a break statement to this block.

Return type:

None

create_continue()[source]

Add a continue statement to this block.

Return type:

None

create_assert(test, msg=None)[source]

Add an assert statement to this block.

Parameters:
  • test (ExpressionLike)

  • msg (ExpressionLike | None)

Return type:

None

create_raise(exc=None, cause=None)[source]

Add a raise statement to this block.

Parameters:
  • exc (ExpressionLike | None)

  • cause (ExpressionLike | None)

Return type:

None

create_if()[source]

Create an If statement, add it to this block, and return it.

Usage:

if_stmt = block.create_if()
if_block = if_stmt.add_if(condition)
if_block.create_return(value)
Return type:

If

create_with(context_expr: ExpressionLike, target: Name | str) tuple[With, Name][source]
create_with(context_expr: ExpressionLike) With

Create a With statement, add it to this block, and return it

Usage:

with_stmt, target = block.create_with(expr, "f")
with_stmt.body.create_return(value)

If target is a str, the name will be reserved. If target is None, only the with_statement will be returned.

Parameters:
  • context_expr (ExpressionLike)

  • target (Name | str | None)

Return type:

With | tuple[With, Name]

create_for(target: str, iterable: ExpressionLike) tuple[For, Name][source]
create_for(target: tuple[str, ...], iterable: ExpressionLike) tuple[For, tuple[Name, ...]]
create_for(target: tuple[Name, ...], iterable: ExpressionLike) tuple[For, tuple[Name, ...]]
create_for(target: Target, iterable: ExpressionLike) tuple[For, Target]

Create a for loop, add it to this block, and return it. The first parameter is the loop variable. If this is a str or tuple[str] then these names will reserved and Name objects created, similar to assign.

The second parameters is an expression that will be iterated over.

Usage:

for_stmt, index = func.body.create_for("i", items)
for_stmt.body.add_statement(some_expr)
Parameters:
  • target (str | tuple[str, ...] | Target)

  • iterable (ExpressionLike)

Return type:

tuple[For, Target]

create_try()[source]

Create a Try statement, add it to this block, and return it.

Add except clauses via Try.create_except().

Usage:

try_stmt = block.create_try()
try_stmt.try_block.add_statement(some_expr)
except_block, e_name = try_stmt.create_except([my_error], "e")
except_block.create_return(value)
Return type:

Try

Scope and name management

class fluent_codegen.codegen.Scope(parent_scope=None)[source]

Bases: object

Track name reservations and assignments within a lexical scope.

Parameters:

parent_scope (Scope | None)

is_name_in_use(name)[source]

Return whether name is already reserved in this scope or any parent.

Parameters:

name (str)

Return type:

bool

is_name_reserved_function_arg(name)[source]

Return whether name is reserved for use as a function argument.

Parameters:

name (str)

Return type:

bool

is_name_reserved(name)[source]

Return whether name is reserved for any purpose in this scope.

Parameters:

name (str)

Return type:

bool

reserve_name(requested, function_arg=False, is_builtin=False)[source]

Reserve a name as being in use in a scope.

Pass function_arg=True if this is a function argument.

Parameters:
  • requested (str)

  • function_arg (bool)

  • is_builtin (bool)

reserve_function_arg_name(name)[source]

Reserve a name for later use as a function argument. This does not result in that name being considered ‘in use’ in the current scope, but will avoid the name being assigned for any use other than as a function argument.

Parameters:

name (str)

has_assignment(name)[source]

Return whether name has been assigned a value in this scope.

Parameters:

name (str)

Return type:

bool

register_assignment(name)[source]

Record that name has been assigned a value in this scope.

Parameters:

name (str)

Return type:

None

create_name(name)[source]

Reserve name (or a variant) and return a Name expression for it.

Parameters:

name (str)

Return type:

Name

name(name)[source]

Return a Name expression for an already-reserved name.

Parameters:

name (str)

Return type:

Name

property enames: Enames[source]

Returns an Enames object, which provides easy access to names as E-objects.

class fluent_codegen.codegen.Name(name, scope)[source]

Bases: Expression

A reference to a named variable that must already be reserved in its Scope.

Parameters:
as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

Name

Functions and classes

class fluent_codegen.codegen.Function(name, args=None, parent_scope=None, decorators=None, return_type=None)[source]

Bases: Scope, Statement

A function definition statement that also acts as a Scope for its body.

Parameters:
property args: Sequence[FunctionArg]

Return the function’s arguments as a read-only sequence.

add_args(args)[source]

Add arguments to the function, with the same validation as in __init__.

Parameters:

args (Sequence[str | FunctionArg])

Return type:

None

as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

stmt

create_return(value)[source]

Add a return statement to the function body.

Parameters:

value (ExpressionLike)

class fluent_codegen.codegen.Class(name, parent_scope=None, bases=None, decorators=None)[source]

Bases: Scope, Statement

A class definition statement that also acts as a Scope for its body.

Parameters:
as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

stmt

class fluent_codegen.codegen.FunctionArg(name, kind=ArgKind.POSITIONAL_OR_KEYWORD, default=None, annotation=None)[source]

Bases: object

A function argument with a name, kind, and optional default value.

Parameters:
name: str
kind: ArgKind = 'positional_or_keyword'
default: Expression | None = None
annotation: Expression | None = None
classmethod positional(name, *, default=None, annotation=None)[source]

Create a positional-only argument.

Parameters:
  • name (str)

  • default (ExpressionLike | None)

  • annotation (ExpressionLike | None)

Return type:

FunctionArg

classmethod keyword(name, *, default=None, annotation=None)[source]

Create a keyword-only argument.

Parameters:
  • name (str)

  • default (ExpressionLike | None)

  • annotation (ExpressionLike | None)

Return type:

FunctionArg

classmethod standard(name, *, default=None, annotation=None)[source]

Create a positional-or-keyword argument (the Python default).

Parameters:
  • name (str)

  • default (ExpressionLike | None)

  • annotation (ExpressionLike | None)

Return type:

FunctionArg

class fluent_codegen.codegen.ArgKind(*values)[source]

Bases: Enum

The kind of a function argument.

POSITIONAL_ONLY = 'positional_only'
POSITIONAL_OR_KEYWORD = 'positional_or_keyword'
KEYWORD_ONLY = 'keyword_only'
class fluent_codegen.codegen.Lambda(args, body)[source]

Bases: Expression

A lambda expression e.g. lambda x: x + 1

Parameters:
as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

expr

fluent_codegen.codegen.create_lambda(args, body)[source]

Create a lambda expression.

The body can be supplied by either an expression, or a callable that will be called with a Lambda object as its only argument. This makes it possible to access the enames object on the Lambda:

create_lambda('x', lambda self: self.enames.x + 1)

Produces: lambda x: x + 1

Parameters:
Return type:

Lambda

Statements

class fluent_codegen.codegen.Statement[source]

Bases: CodeGenAst

Base class for code-generation nodes that represent Python statements.

class fluent_codegen.codegen.Assignment(target, value, /, *, type_hint=None)[source]

Bases: Statement

A variable assignment statement, optionally with a type annotation.

Parameters:
names: list[str]
target: Target
as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

class fluent_codegen.codegen.Annotation(name, annotation)[source]

Bases: Statement

A bare type annotation without a value, e.g. x: int.

Parameters:
as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

class fluent_codegen.codegen.Return(value)[source]

Bases: Statement

A return statement.

Parameters:

value (Expression)

as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

class fluent_codegen.codegen.Break[source]

Bases: Statement

A break statement.

as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

class fluent_codegen.codegen.Continue[source]

Bases: Statement

A continue statement.

as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

class fluent_codegen.codegen.Assert(test, msg=None)[source]

Bases: Statement

An assert statement with an optional message.

Parameters:
as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

class fluent_codegen.codegen.Raise(exc=None, cause=None)[source]

Bases: Statement

A raise statement.

Supports:

  • raise exc

  • raise exc from cause

  • bare raise (re-raise the current exception)

Parameters:
as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

class fluent_codegen.codegen.If(parent_scope, parent_block=None)[source]

Bases: Statement

A compound if/elif/else statement.

Parameters:
  • parent_scope (Scope)

  • parent_block (Block | None)

if_blocks: list[Block]
conditions: list[Expression]
create_if_branch(condition)[source]

Create new if branch with a condition.

Parameters:

condition (ExpressionLike)

Return type:

Block

finalize()[source]

Return a simplified node: the else block if there are no conditions, otherwise self.

Return type:

Block | Statement

as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

If

class fluent_codegen.codegen.With(context_expr, target=None, *, parent_scope, parent_block=None)[source]

Bases: Statement

A with statement.

Parameters:
as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

With

class fluent_codegen.codegen.For(target, iterable, *, parent_scope, parent_block=None)[source]

Bases: Statement

A for loop, with optional else clause.

Parameters:
target: Target
as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

For

class fluent_codegen.codegen.Try(parent_scope, *, parent_block=None)[source]

Bases: Statement

A try/except/else/finally statement.

Except clauses are added incrementally via create_except(), similar to how If.create_if_branch() works.

Parameters:
  • parent_scope (Scope)

  • parent_block (Block | None)

except_blocks: list[Block]
except_types: list[list[Expression]]
except_names: list[str | None]
create_except(catch_exceptions: Sequence[ExpressionLike], *, name: str | Name) tuple[Block, Name][source]
create_except(catch_exceptions: Sequence[ExpressionLike]) Block

Add an except clause and return its body block.

catch_exceptions is the list of exception types to catch (a single-element list produces except Foo:, multiple elements produce except (Foo, Bar):).

name, if given, becomes the as target (except Foo as name:). If it is passed as a str it is reserved in the scope. It is returned as a Name object.

Parameters:
Return type:

Block | tuple[Block, Name]

as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

Try

class fluent_codegen.codegen.Import(module, as_)[source]

Bases: Statement

Simple import statements, supporting: - import foo - import foo as bar - import foo.bar - import foo.bar as baz

Use via Block.create_import

We deliberately don’t support multiple imports - these should be cleaned up later using a linter on the generated code, if desired.

Parameters:
as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

AST

class fluent_codegen.codegen.ImportFrom(from_module, import_, as_)[source]

Bases: Statement

from ... import statement, supporting:

  • from foo import bar

  • from foo import bar as baz

Use via Block.create_import_from

We deliberately don’t support multiple imports - these should be cleaned up later using a linter on the generated code, if desired.

Parameters:
  • from_module (str)

  • import_ (str)

  • as_ (Name | None)

as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

AST

Expressions

class fluent_codegen.codegen.Expression[source]

Bases: CodeGenAst

Base class for code-generation nodes that represent Python expressions.

abstractmethod as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

expr

classmethod from_e(obj)[source]
Parameters:

obj (Expression | E)

Return type:

Expression

attr(attribute, /)[source]

Return an Attr expression for accessing attribute on this expression.

Parameters:

attribute (str)

Return type:

Attr

call(args=None, kwargs=None)[source]

Return a Call expression invoking this expression.

Parameters:
Return type:

Call

method_call(attribute, args=None, kwargs=None)[source]

Return a Call expression for a method call on this expression.

Parameters:
Return type:

Call

subscript(slice, /)[source]

Return a Subscript expression indexing this expression.

Parameters:

slice (ExpressionLike)

Return type:

Subscript

add(other, /)[source]

Return an Add (+) expression.

Parameters:

other (ExpressionLike)

Return type:

Add

sub(other, /)[source]

Return a Sub (-) expression.

Parameters:

other (ExpressionLike)

Return type:

Sub

mul(other, /)[source]

Return a Mul (*) expression.

Parameters:

other (ExpressionLike)

Return type:

Mul

div(other, /)[source]

Return a Div (/) expression.

Parameters:

other (ExpressionLike)

Return type:

Div

floordiv(other, /)[source]

Return a FloorDiv (//) expression.

Parameters:

other (ExpressionLike)

Return type:

FloorDiv

mod(other, /)[source]

Return a Mod (%) expression.

Parameters:

other (ExpressionLike)

Return type:

Mod

pow(other, /)[source]

Return a Pow (**) expression.

Parameters:

other (ExpressionLike)

Return type:

Pow

matmul(other, /)[source]

Return a MatMul (@) expression.

Parameters:

other (ExpressionLike)

Return type:

MatMul

bitand(other, /)[source]

Return a BitAnd (&) expression.

Parameters:

other (ExpressionLike)

Return type:

BitAnd

bitor(other, /)[source]

Return a BitOr (|) expression.

Parameters:

other (ExpressionLike)

Return type:

BitOr

xor(other, /)[source]

Return a BitXor (^) expression.

Parameters:

other (ExpressionLike)

Return type:

BitXor

lshift(other, /)[source]

Return a LShift (<<) expression.

Parameters:

other (ExpressionLike)

Return type:

LShift

rshift(other, /)[source]

Return a RShift (>>) expression.

Parameters:

other (ExpressionLike)

Return type:

RShift

invert()[source]

Return an Invert (~self) expression.

Return type:

Invert

eq(other, /)[source]

Return an Equals (==) expression.

Parameters:

other (ExpressionLike)

Return type:

Equals

ne(other, /)[source]

Return a NotEquals (!=) expression.

Parameters:

other (ExpressionLike)

Return type:

NotEquals

lt(other, /)[source]

Return a Lt (<) expression.

Parameters:

other (ExpressionLike)

Return type:

Lt

gt(other, /)[source]

Return a Gt (>) expression.

Parameters:

other (ExpressionLike)

Return type:

Gt

le(other, /)[source]

Return a LtE (<=) expression.

Parameters:

other (ExpressionLike)

Return type:

LtE

ge(other, /)[source]

Return a GtE (>=) expression.

Parameters:

other (ExpressionLike)

Return type:

GtE

and_(other, /)[source]

Return an And (and) expression.

Parameters:

other (ExpressionLike)

Return type:

And

or_(other, /)[source]

Return an Or (or) expression.

Parameters:

other (ExpressionLike)

Return type:

Or

in_(other, /)[source]

Return an In (in) expression.

Parameters:

other (ExpressionLike)

Return type:

In

not_in(other, /)[source]

Return a NotIn (not in) expression.

Parameters:

other (ExpressionLike)

Return type:

NotIn

is_(other, /)[source]

Return an Is (is) expression.

Parameters:

other (ExpressionLike)

Return type:

Is

is_not(other, /)[source]

Return an IsNot (is not) expression.

Parameters:

other (ExpressionLike)

Return type:

IsNot

not_()[source]

Return a Not (not self) expression.

Return type:

Not

pos()[source]

Return a UAdd (+self) expression.

Return type:

UAdd

neg()[source]

Return a USub (-self) expression.

Return type:

USub

starred()[source]

Return a Starred (*self) unpacking expression.

Return type:

Starred

named(name)[source]

Return the expression as a named expression (walrus operator)

Parameters:

name (Name)

Return type:

NamedExpr

property e: E[source]

Returns this Expression as an E-object for easier expression generation.

Literal types

class fluent_codegen.codegen.String(string_value)[source]

Bases: Expression

A string literal expression.

Parameters:

string_value (str)

as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

expr

class fluent_codegen.codegen.Number(number)[source]

Bases: Expression

A numeric literal expression (int or float).

Parameters:

number (int | float)

as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

expr

class fluent_codegen.codegen.Bool(value)[source]

Bases: Expression

A boolean literal expression (True or False).

Parameters:

value (bool)

as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

expr

class fluent_codegen.codegen.Bytes(value)[source]

Bases: Expression

A bytes literal expression.

Parameters:

value (bytes)

as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

expr

class fluent_codegen.codegen.NoneExpr[source]

Bases: Expression

A None literal expression.

as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

expr

class fluent_codegen.codegen.List(items)[source]

Bases: Expression

A list literal expression.

Parameters:

items (Sequence[Expression])

as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

expr

class fluent_codegen.codegen.Tuple(items)[source]

Bases: Expression

A tuple literal expression.

Parameters:

items (Sequence[Expression])

as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

expr

class fluent_codegen.codegen.Set(items)[source]

Bases: Expression

A set literal expression, using set([]) for the empty case.

Parameters:

items (Sequence[Expression])

as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

expr

class fluent_codegen.codegen.Dict(pairs)[source]

Bases: Expression

A dict literal expression.

Parameters:

pairs (Sequence[tuple[Expression, Expression]])

as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

expr

Access and call expressions

class fluent_codegen.codegen.Attr(value, attribute)[source]

Bases: Expression

An attribute access expression (e.g. obj.attr).

Parameters:
as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

expr

class fluent_codegen.codegen.Call(value, args, kwargs)[source]

Bases: Expression

A function or method call expression.

Parameters:
as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

expr

class fluent_codegen.codegen.Subscript(value, slice)[source]

Bases: Expression

A subscript (indexing) expression (e.g. obj[key]).

Parameters:
as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

expr

class fluent_codegen.codegen.Slice(start=None, stop=None, step=None)[source]

Bases: Expression

A slice expression (e.g. 0:10, ::2, 1:-1).

Used as the slice argument to Subscript. All three components — start, stop, and step — are optional.

Parameters:
as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

expr

class fluent_codegen.codegen.Starred(value)[source]

Bases: Expression

A starred (unpacking) expression (e.g. *args).

Parameters:

value (Expression)

as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

expr

Comprehensions

class fluent_codegen.codegen.Comprehension(target, iter)[source]

Bases: object

Parameters:
class fluent_codegen.codegen.ListComp(element, generators, ifs)[source]

Bases: _EltComprehensionBase

A list comprehension expression, e.g. [x + 1 for x in items].

Parameters:
as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

expr

class fluent_codegen.codegen.SetComp(element, generators, ifs)[source]

Bases: _EltComprehensionBase

A set comprehension expression, e.g. {x + 1 for x in items}.

Parameters:
as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

expr

class fluent_codegen.codegen.DictComp(key, value, generators, ifs)[source]

Bases: Expression

A dict comprehension expression, e.g. {k: v for k, v in items}.

Parameters:
as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

expr

class fluent_codegen.codegen.GeneratorExpr(element, generators, ifs)[source]

Bases: _EltComprehensionBase

A generator expression, e.g. (x + 1 for x in items).

Parameters:
as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

expr

fluent_codegen.codegen.list_comprehension(*, iterable, target, element, condition=None)[source]

Create a ListComp (list comprehension) expression.

e.g.:

data = auto([1, 2, 3])
list_comprehension(
    iterable=data,
    target=(loop_var := mod.scope.create_name("item")),
    element=loop_var.e + 1,
    condition=loop_var.e > 0
)

This produces: [item + 1 for item in [1, 2, 3] if item > 0]

Parameters:
  • iterable (ExpressionLike)

  • target (Target)

  • element (ExpressionLike)

  • condition (ExpressionLike | None)

Return type:

ListComp

fluent_codegen.codegen.set_comprehension(*, iterable, target, element, condition=None)[source]

Create a SetComp (set comprehension) expression.

e.g.:

data = auto([1, 2, 3])
set_comprehension(
    iterable=data,
    target=(loop_var := mod.scope.create_name("item")),
    element=loop_var.e + 1,
    condition=loop_var.e > 0
)

This produces: {item + 1 for item in [1, 2, 3] if item > 0}

Parameters:
  • iterable (ExpressionLike)

  • target (Target)

  • element (ExpressionLike)

  • condition (ExpressionLike | None)

Return type:

SetComp

fluent_codegen.codegen.dict_comprehension(*, iterable, target, key, value, condition=None)[source]

Create a DictComp (dict comprehension) expression.

e.g.:

dict_comprehension(
    iterable=items,
    target=(
        (key_var := mod.scope.create_name("k")),
        (value_var := mod.scope.create_name("v")),
    ),
    key=key_var.e + "_x",
    value=value_var.e + 1,
)

This produces: {k + '_x': v + 1 for k, v in items}

Parameters:
  • iterable (ExpressionLike)

  • target (Target)

  • key (ExpressionLike)

  • value (ExpressionLike)

  • condition (ExpressionLike | None)

Return type:

DictComp

fluent_codegen.codegen.generator_expression(*, iterable, target, element, condition=None)[source]

Create a SetComp (set comprehension) expression.

e.g.:

data = auto([1, 2, 3])
my_func = mod.scope.create_name("my_func")
my_func.e(generator_expression(
    iterable=data,
    target=(loop_var := mod.scope.create_name("item")),
    element=loop_var.e + 1,
    condition=loop_var.e > 0
)

This produces: my_func((item + 1 for item in [1, 2, 3] if item > 0))

Parameters:
  • iterable (ExpressionLike)

  • target (Target)

  • element (ExpressionLike)

  • condition (ExpressionLike | None)

Return type:

GeneratorExpr

String joining

class fluent_codegen.codegen.StringJoinBase(parts)[source]

Bases: Expression

Base class for string concatenation expressions.

Parameters:

parts (Sequence[Expression])

classmethod build(parts)[source]

Build a string join operation, but return a simpler expression if possible.

Parameters:

parts (Sequence[Expression])

Return type:

StringJoinBase | Expression

class fluent_codegen.codegen.FStringJoin(parts)[source]

Bases: StringJoinBase

Join string parts using an f-string expression.

Parameters:

parts (Sequence[Expression])

as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

expr

class fluent_codegen.codegen.ConcatJoin(parts)[source]

Bases: StringJoinBase

Join string parts using + concatenation.

Parameters:

parts (Sequence[Expression])

as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

expr

fluent_codegen.codegen.StringJoin

Alias for FStringJoin (the default string-join strategy).

Arithmetic operators

class fluent_codegen.codegen.Add(left, right)[source]

Bases: ArithOp

Addition (+) operator.

Parameters:
op

alias of Add

class fluent_codegen.codegen.Sub(left, right)[source]

Bases: ArithOp

Subtraction (-) operator.

Parameters:
op

alias of Sub

class fluent_codegen.codegen.Mul(left, right)[source]

Bases: ArithOp

Multiplication (*) operator.

Parameters:
op

alias of Mult

class fluent_codegen.codegen.Div(left, right)[source]

Bases: ArithOp

True division (/) operator.

Parameters:
op

alias of Div

class fluent_codegen.codegen.FloorDiv(left, right)[source]

Bases: ArithOp

Floor division (//) operator.

Parameters:
op

alias of FloorDiv

class fluent_codegen.codegen.Mod(left, right)[source]

Bases: ArithOp

Modulo (%) operator.

Parameters:
op

alias of Mod

class fluent_codegen.codegen.Pow(left, right)[source]

Bases: ArithOp

Exponentiation (**) operator.

Parameters:
op

alias of Pow

class fluent_codegen.codegen.MatMul(left, right)[source]

Bases: ArithOp

Matrix multiplication (@) operator.

Parameters:
op

alias of MatMult

Comparison operators

class fluent_codegen.codegen.Equals(left, right)[source]

Bases: CompareOp

Equality (==) comparison.

Parameters:
op

alias of Eq

class fluent_codegen.codegen.NotEquals(left, right)[source]

Bases: CompareOp

Inequality (!=) comparison.

Parameters:
op

alias of NotEq

class fluent_codegen.codegen.Lt(left, right)[source]

Bases: CompareOp

Less-than (<) comparison.

Parameters:
op

alias of Lt

class fluent_codegen.codegen.Gt(left, right)[source]

Bases: CompareOp

Greater-than (>) comparison.

Parameters:
op

alias of Gt

class fluent_codegen.codegen.LtE(left, right)[source]

Bases: CompareOp

Less-than-or-equal (<=) comparison.

Parameters:
op

alias of LtE

class fluent_codegen.codegen.GtE(left, right)[source]

Bases: CompareOp

Greater-than-or-equal (>=) comparison.

Parameters:
op

alias of GtE

class fluent_codegen.codegen.In(left, right)[source]

Bases: CompareOp

Membership (in) comparison.

Parameters:
op

alias of In

class fluent_codegen.codegen.NotIn(left, right)[source]

Bases: CompareOp

Non-membership (not in) comparison.

Parameters:
op

alias of NotIn

Boolean operators

class fluent_codegen.codegen.And(left, right)[source]

Bases: BoolOp

Logical and operator.

Parameters:
op

alias of And

class fluent_codegen.codegen.Or(left, right)[source]

Bases: BoolOp

Logical or operator.

Parameters:
op

alias of Or

Base classes

class fluent_codegen.codegen.BinaryOperator(left, right)[source]

Bases: Expression

Base class for binary operator expressions with a left and right operand.

Parameters:
class fluent_codegen.codegen.ArithOp(left, right)[source]

Bases: BinaryOperator, ABC

Arithmetic binary operator (ast.BinOp).

Parameters:
op: ClassVar[type[operator]]
as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

expr

class fluent_codegen.codegen.CompareOp(left, right)[source]

Bases: BinaryOperator, ABC

Comparison operator (ast.Compare).

Parameters:
op: ClassVar[type[cmpop]]
as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

expr

class fluent_codegen.codegen.BoolOp(left, right)[source]

Bases: BinaryOperator, ABC

Boolean operator (and / or).

Parameters:
op: ClassVar[type[boolop]]
as_ast(*, include_comments=False)[source]
Parameters:

include_comments (bool)

Return type:

expr

Utility functions

fluent_codegen.codegen.auto(value: bool) Bool[source]
fluent_codegen.codegen.auto(value: str) String
fluent_codegen.codegen.auto(value: bytes) Bytes
fluent_codegen.codegen.auto(value: int) Number
fluent_codegen.codegen.auto(value: float) Number
fluent_codegen.codegen.auto(value: None) NoneExpr
fluent_codegen.codegen.auto(value: slice[Autoable]) Slice
fluent_codegen.codegen.auto(value: Expression) Expression
fluent_codegen.codegen.auto(value: E) Expression
fluent_codegen.codegen.auto(value: list[Autoable]) List
fluent_codegen.codegen.auto(value: tuple[Autoable, ...]) Tuple
fluent_codegen.codegen.auto(value: set[Autoable]) Set
fluent_codegen.codegen.auto(value: dict[Autoable, Autoable]) Dict

Create a codegen Expression from a plain Python object.

Supports bool, str, bytes, int, float, None, slice, and recursively list, tuple, set, and dict.

It also supports a mixture - containers than have both plain Python objects and values that are already Expression or E-objects.

Parameters:

value (Autoable)

Return type:

Expression

class fluent_codegen.codegen.constants[source]

Bases: object

Useful pre-made Expression constants

None_: NoneExpr = <fluent_codegen.codegen.NoneExpr object>
True_: Bool = Bool(True)
False_: Bool = Bool(False)
fluent_codegen.codegen.function_call(function_name, args, kwargs, scope)[source]

Create a function call expression, validating that the name exists in scope.

Parameters:
Return type:

Expression

fluent_codegen.codegen.method_call(obj, method_name, args, kwargs)[source]

Create a method call expression on obj.

Parameters:
fluent_codegen.codegen.named(name, value)[source]

Create a NamedExpr from an Expression or E-object:

x = mod.scope.create_name("x")
value = codegen.auto(1).e + 1
named_val = codegen.named(x, value)

Produces:

(x := 1 + 1)
Parameters:
  • name (Name)

  • value (ExpressionLike)

Return type:

NamedExpr

fluent_codegen.codegen.cleanup_name(name)[source]

Convert name to a allowable identifier

Parameters:

name (str)

Return type:

str

fluent_codegen.codegen.traverse(ast_node, func)[source]

Apply ‘func’ to ast_node (which is ast.* object)

Parameters:
fluent_codegen.codegen.simplify(codegen_ast, simplifier)[source]

Repeatedly apply simplifier to codegen_ast until no more changes are made.

Parameters:
  • codegen_ast (CodeGenAst | CodeGenAstList)

  • simplifier (Callable[[CodeGenAst | CodeGenAstList, list[bool]], CodeGenAst])

fluent_codegen.codegen.rewriting_traverse(node, func, _visited=None)[source]

Apply ‘func’ to node and all sub CodeGenAst nodes.

Discovers child nodes by introspecting instance attributes rather than relying on a manually-maintained list. A visited set (keyed by id()) prevents infinite recursion through circular references (e.g. Block.scope → Function → body → Block).

Parameters:
  • node (CodeGenAst | CodeGenAstList | Sequence[CodeGenAst | CodeGenAstList])

  • func (Callable[[CodeGenAst | CodeGenAstList], CodeGenAst | CodeGenAstList])

  • _visited (set[int] | None)

fluent_codegen.codegen.morph_into(item, new_item)[source]

Mutate item in-place to behave identically to new_item while preserving identity.

Parameters:
Return type:

None

fluent_codegen.codegen.SENSITIVE_FUNCTIONS = {'__build_class__', '__import__', 'apply', 'compile', 'eval', 'exec', 'execfile', 'exit', 'file', 'globals', 'locals', 'object', 'open', 'reload', 'type'}

Build an unordered collection of unique elements.

Dead-code elimination

fluent_codegen.remove_unused_assignments.remove_unused_assignments(func)[source]

Remove statements that assign to a name which is never read.

Works recursively: if removing x = y makes y unused, it will be removed too. Raises AssertionError on nested scopes.

Parameters:

func (Function)

Return type:

None