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,CodeGenAstTop-level module block with its own
Scopepre-loaded with builtins.- Parameters:
reserve_builtins (bool)
- class fluent_codegen.codegen.Block(scope, parent_block=None)[source]
Bases:
CodeGenAstListAn ordered sequence of statements sharing a common
Scope.- add_comment(text, *, wrap=None)[source]
Add a
# textcomment 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).
- add_statements(statements)[source]
Append multiple statements to this block.
This is a convenience wrapper around
add_statement():block.add_statements([stmt_a, stmt_b, stmt_c]) # equivalent to: block.add_statement(stmt_a) block.add_statement(stmt_b) block.add_statement(stmt_c)
- create_import(module, as_=None)[source]
Create an
importstatement, reserve the resulting name, and add it to this block.
- create_import_from(*, from_, import_, as_=None)[source]
Create a
from ... importstatement, reserve the resulting name, and add it to this block.
- 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
- 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 newName:result = block.assign("x", some_expr) # equivalent to: # x = scope.create_name("x") # block.create_assignment(x, some_expr)
When target is a
tupleofstr, reserves each name and creates a tuple-unpacking assignment, returning a tuple ofNameobjects: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)
- 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, orSubscript(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.
- 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
- 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.
- 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.
- create_return(value)[source]
Add a
returnstatement to this block.- Parameters:
value (ExpressionLike)
- Return type:
None
- create_assert(test, msg=None)[source]
Add an
assertstatement to this block.- Parameters:
test (ExpressionLike)
msg (ExpressionLike | None)
- Return type:
None
- create_raise(exc=None, cause=None)[source]
Add a
raisestatement 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:
- 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.
- 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
forloop, 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 parameter 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)
- create_try()[source]
Create a Try statement, add it to this block, and return it.
Add
exceptclauses viaTry.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:
Scope and name management
- class fluent_codegen.codegen.Scope(parent_scope=None)[source]
Bases:
objectTrack name reservations and assignments within a lexical scope.
- Parameters:
parent_scope (Scope | None)
- is_name_reserved_function_arg(name)[source]
Return whether name is reserved for use as a function argument.
- 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.
- 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)
- register_assignment(name)[source]
Record that name has been assigned a value in this scope.
- Parameters:
name (str)
- Return type:
None
Functions and classes
- class fluent_codegen.codegen.Function(name, args=None, parent_scope=None, decorators=None, return_type=None)[source]
-
A function definition statement that also acts as a
Scopefor its body.- Parameters:
name (str)
args (Sequence[str | FunctionArg] | None)
parent_scope (Scope | None)
decorators (Sequence[Expression] | None)
return_type (Expression | None)
- 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
- class fluent_codegen.codegen.Class(name, parent_scope=None, bases=None, decorators=None)[source]
-
A class definition statement that also acts as a
Scopefor its body.- Parameters:
name (str)
parent_scope (Scope | None)
bases (Sequence[Expression] | None)
decorators (Sequence[Expression] | None)
- class fluent_codegen.codegen.FunctionArg(name, kind=ArgKind.POSITIONAL_OR_KEYWORD, default=None, annotation=None)[source]
Bases:
objectA function argument with a name, kind, and optional default value.
- Parameters:
name (str)
kind (ArgKind)
default (Expression | None)
annotation (Expression | None)
- 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:
- classmethod keyword(name, *, default=None, annotation=None)[source]
Create a keyword-only argument.
- Parameters:
name (str)
default (ExpressionLike | None)
annotation (ExpressionLike | None)
- Return type:
- class fluent_codegen.codegen.ArgKind(*values)[source]
Bases:
EnumThe 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:
ExpressionA lambda expression e.g. lambda x: x + 1
- Parameters:
args (Sequence[str | FunctionArg])
body (Expression)
- 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
Statements
- class fluent_codegen.codegen.Statement[source]
Bases:
CodeGenAstBase class for code-generation nodes that represent Python statements.
- class fluent_codegen.codegen.Assignment(target, value, /, *, type_hint=None)[source]
Bases:
StatementA variable assignment statement, optionally with a type annotation.
- Parameters:
target (Target)
value (Expression)
type_hint (Expression | None)
- target: Target
- class fluent_codegen.codegen.Annotation(name, annotation)[source]
Bases:
StatementA bare type annotation without a value, e.g.
x: int.- Parameters:
name (str)
annotation (Expression)
- class fluent_codegen.codegen.Return(value)[source]
Bases:
StatementA
returnstatement.- Parameters:
value (Expression)
- class fluent_codegen.codegen.Assert(test, msg=None)[source]
Bases:
StatementAn
assertstatement with an optional message.- Parameters:
test (Expression)
msg (Expression | None)
- class fluent_codegen.codegen.Raise(exc=None, cause=None)[source]
Bases:
StatementA
raisestatement.Supports:
raise excraise exc from causebare
raise(re-raise the current exception)
- Parameters:
exc (Expression | None)
cause (Expression | None)
- class fluent_codegen.codegen.If(parent_scope, parent_block=None)[source]
Bases:
StatementA compound
if/elif/elsestatement.- conditions: list[Expression]
- create_if_branch(condition)[source]
Create new if branch with a condition.
- Parameters:
condition (ExpressionLike)
- Return type:
- class fluent_codegen.codegen.With(context_expr, target=None, *, parent_scope, parent_block=None)[source]
Bases:
StatementA
withstatement.- Parameters:
context_expr (Expression)
target (Name | None)
parent_scope (Scope)
parent_block (Block | None)
- class fluent_codegen.codegen.For(target, iterable, *, parent_scope, parent_block=None)[source]
Bases:
StatementA
forloop, with optionalelseclause.- Parameters:
target (Target)
iterable (Expression)
parent_scope (Scope)
parent_block (Block | None)
- target: Target
- class fluent_codegen.codegen.Try(parent_scope, *, parent_block=None)[source]
Bases:
StatementA
try/except/else/finallystatement.Except clauses are added incrementally via
create_except(), similar to howIf.create_if_branch()works.- except_types: list[list[Expression]]
- create_except(catch_exceptions: Sequence[ExpressionLike], *, name: str | Name) tuple[Block, Name][source]
- create_except(catch_exceptions: Sequence[ExpressionLike]) Block
Add an
exceptclause and return its body block.catch_exceptions is the list of exception types to catch (a single-element list produces
except Foo:, multiple elements produceexcept (Foo, Bar):).name, if given, becomes the
astarget (except Foo as name:). If it is passed as a str it is reserved in the scope. It is returned as a Name object.
- class fluent_codegen.codegen.Import(module, as_)[source]
Bases:
StatementSimple 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.
- class fluent_codegen.codegen.ImportFrom(from_module, import_, as_)[source]
Bases:
Statementfrom ... importstatement, supporting:from foo import barfrom 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.
Expressions
- class fluent_codegen.codegen.Expression[source]
Bases:
CodeGenAstBase 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:
- method_call(attribute, args=None, kwargs=None)[source]
Return a
Callexpression for a method call on this expression.
- subscript(slice, /)[source]
Return a
Subscriptexpression indexing this expression.- Parameters:
slice (ExpressionLike)
- Return type:
- add(other, /)[source]
Return an
Add(+) expression.- Parameters:
other (ExpressionLike)
- Return type:
- floordiv(other, /)[source]
Return a
FloorDiv(//) expression.- Parameters:
other (ExpressionLike)
- Return type:
- pow(other, /)[source]
Return a
Pow(**) expression.- Parameters:
other (ExpressionLike)
- Return type:
- matmul(other, /)[source]
Return a
MatMul(@) expression.- Parameters:
other (ExpressionLike)
- Return type:
- 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
- eq(other, /)[source]
Return an
Equals(==) expression.- Parameters:
other (ExpressionLike)
- Return type:
- ne(other, /)[source]
Return a
NotEquals(!=) expression.- Parameters:
other (ExpressionLike)
- Return type:
- and_(other, /)[source]
Return an
And(and) expression.- Parameters:
other (ExpressionLike)
- Return type:
- or_(other, /)[source]
Return an
Or(or) expression.- Parameters:
other (ExpressionLike)
- Return type:
- in_(other, /)[source]
Return an
In(in) expression.- Parameters:
other (ExpressionLike)
- Return type:
- not_in(other, /)[source]
Return a
NotIn(not in) expression.- Parameters:
other (ExpressionLike)
- Return type:
- 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
Literal types
- class fluent_codegen.codegen.String(string_value)[source]
Bases:
ExpressionA string literal expression.
- Parameters:
string_value (str)
- class fluent_codegen.codegen.Number(number)[source]
Bases:
ExpressionA numeric literal expression (
intorfloat).
- class fluent_codegen.codegen.Bool(value)[source]
Bases:
ExpressionA boolean literal expression (
TrueorFalse).- Parameters:
value (bool)
- class fluent_codegen.codegen.Bytes(value)[source]
Bases:
ExpressionA bytes literal expression.
- Parameters:
value (bytes)
- class fluent_codegen.codegen.NoneExpr[source]
Bases:
ExpressionA
Noneliteral expression.
- class fluent_codegen.codegen.List(items)[source]
Bases:
ExpressionA list literal expression.
- Parameters:
items (Sequence[Expression])
- class fluent_codegen.codegen.Tuple(items)[source]
Bases:
ExpressionA tuple literal expression.
- Parameters:
items (Sequence[Expression])
- class fluent_codegen.codegen.Set(items)[source]
Bases:
ExpressionA set literal expression, using
set([])for the empty case.- Parameters:
items (Sequence[Expression])
- class fluent_codegen.codegen.Dict(pairs)[source]
Bases:
ExpressionA dict literal expression.
- Parameters:
pairs (Sequence[tuple[Expression, Expression]])
Access and call expressions
- class fluent_codegen.codegen.Attr(value, attribute)[source]
Bases:
ExpressionAn attribute access expression (e.g.
obj.attr).- Parameters:
value (Expression)
attribute (str)
- class fluent_codegen.codegen.Call(value, args, kwargs)[source]
Bases:
ExpressionA function or method call expression.
- Parameters:
value (Expression)
args (Sequence[Expression])
kwargs (Mapping[str, Expression])
- class fluent_codegen.codegen.Subscript(value, slice)[source]
Bases:
ExpressionA subscript (indexing) expression (e.g.
obj[key]).- Parameters:
value (Expression)
slice (Expression)
- class fluent_codegen.codegen.Slice(start=None, stop=None, step=None)[source]
Bases:
ExpressionA 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:
start (Expression | None)
stop (Expression | None)
step (Expression | None)
- class fluent_codegen.codegen.Starred(value)[source]
Bases:
ExpressionA starred (unpacking) expression (e.g.
*args).- Parameters:
value (Expression)
Comprehensions
- class fluent_codegen.codegen.Comprehension(target, iter)[source]
Bases:
object- Parameters:
target (Target)
iter (Expression)
- class fluent_codegen.codegen.ListComp(element, generators, ifs)[source]
Bases:
_EltComprehensionBaseA list comprehension expression, e.g.
[x + 1 for x in items].- Parameters:
element (Expression)
generators (Sequence[Comprehension])
ifs (Sequence[Expression])
- class fluent_codegen.codegen.SetComp(element, generators, ifs)[source]
Bases:
_EltComprehensionBaseA set comprehension expression, e.g.
{x + 1 for x in items}.- Parameters:
element (Expression)
generators (Sequence[Comprehension])
ifs (Sequence[Expression])
- class fluent_codegen.codegen.DictComp(key, value, generators, ifs)[source]
Bases:
ExpressionA dict comprehension expression, e.g.
{k: v for k, v in items}.- Parameters:
key (Expression)
value (Expression)
generators (Sequence[Comprehension])
ifs (Sequence[Expression])
- class fluent_codegen.codegen.GeneratorExpr(element, generators, ifs)[source]
Bases:
_EltComprehensionBaseA generator expression, e.g.
(x + 1 for x in items).- Parameters:
element (Expression)
generators (Sequence[Comprehension])
ifs (Sequence[Expression])
- 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:
- 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:
- 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:
- 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:
String joining
- class fluent_codegen.codegen.StringJoinBase(parts)[source]
Bases:
ExpressionBase 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:
- class fluent_codegen.codegen.FStringJoin(parts)[source]
Bases:
StringJoinBaseJoin string parts using an f-string expression.
- Parameters:
parts (Sequence[Expression])
- class fluent_codegen.codegen.ConcatJoin(parts)[source]
Bases:
StringJoinBaseJoin string parts using
+concatenation.- Parameters:
parts (Sequence[Expression])
- fluent_codegen.codegen.StringJoin
Alias for
FStringJoin(the default string-join strategy).
Arithmetic operators
- class fluent_codegen.codegen.Add(left, right)[source]
Bases:
ArithOpAddition (
+) operator.- Parameters:
left (Expression)
right (Expression)
- class fluent_codegen.codegen.Sub(left, right)[source]
Bases:
ArithOpSubtraction (
-) operator.- Parameters:
left (Expression)
right (Expression)
- class fluent_codegen.codegen.Mul(left, right)[source]
Bases:
ArithOpMultiplication (
*) operator.- Parameters:
left (Expression)
right (Expression)
- class fluent_codegen.codegen.Div(left, right)[source]
Bases:
ArithOpTrue division (
/) operator.- Parameters:
left (Expression)
right (Expression)
- class fluent_codegen.codegen.FloorDiv(left, right)[source]
Bases:
ArithOpFloor division (
//) operator.- Parameters:
left (Expression)
right (Expression)
- class fluent_codegen.codegen.Mod(left, right)[source]
Bases:
ArithOpModulo (
%) operator.- Parameters:
left (Expression)
right (Expression)
- class fluent_codegen.codegen.Pow(left, right)[source]
Bases:
ArithOpExponentiation (
**) operator.- Parameters:
left (Expression)
right (Expression)
- class fluent_codegen.codegen.MatMul(left, right)[source]
Bases:
ArithOpMatrix multiplication (
@) operator.- Parameters:
left (Expression)
right (Expression)
Comparison operators
- class fluent_codegen.codegen.Equals(left, right)[source]
Bases:
CompareOpEquality (
==) comparison.- Parameters:
left (Expression)
right (Expression)
- class fluent_codegen.codegen.NotEquals(left, right)[source]
Bases:
CompareOpInequality (
!=) comparison.- Parameters:
left (Expression)
right (Expression)
- class fluent_codegen.codegen.Lt(left, right)[source]
Bases:
CompareOpLess-than (
<) comparison.- Parameters:
left (Expression)
right (Expression)
- class fluent_codegen.codegen.Gt(left, right)[source]
Bases:
CompareOpGreater-than (
>) comparison.- Parameters:
left (Expression)
right (Expression)
- class fluent_codegen.codegen.LtE(left, right)[source]
Bases:
CompareOpLess-than-or-equal (
<=) comparison.- Parameters:
left (Expression)
right (Expression)
- class fluent_codegen.codegen.GtE(left, right)[source]
Bases:
CompareOpGreater-than-or-equal (
>=) comparison.- Parameters:
left (Expression)
right (Expression)
- class fluent_codegen.codegen.In(left, right)[source]
Bases:
CompareOpMembership (
in) comparison.- Parameters:
left (Expression)
right (Expression)
- class fluent_codegen.codegen.NotIn(left, right)[source]
Bases:
CompareOpNon-membership (
not in) comparison.- Parameters:
left (Expression)
right (Expression)
Boolean operators
- class fluent_codegen.codegen.And(left, right)[source]
Bases:
BoolOpLogical
andoperator.- Parameters:
left (Expression)
right (Expression)
- class fluent_codegen.codegen.Or(left, right)[source]
Bases:
BoolOpLogical
oroperator.- Parameters:
left (Expression)
right (Expression)
Base classes
- class fluent_codegen.codegen.BinaryOperator(left, right)[source]
Bases:
ExpressionBase class for binary operator expressions with a left and right operand.
- Parameters:
left (Expression)
right (Expression)
- class fluent_codegen.codegen.ArithOp(left, right)[source]
Bases:
BinaryOperator,ABCArithmetic binary operator (ast.BinOp).
- Parameters:
left (Expression)
right (Expression)
- class fluent_codegen.codegen.CompareOp(left, right)[source]
Bases:
BinaryOperator,ABCComparison operator (ast.Compare).
- Parameters:
left (Expression)
right (Expression)
- class fluent_codegen.codegen.BoolOp(left, right)[source]
Bases:
BinaryOperator,ABCBoolean operator (
and/or).- Parameters:
left (Expression)
right (Expression)
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:
- fluent_codegen.codegen.function_call(function_name, args, kwargs, scope)[source]
Create a function call expression, validating that the name exists in scope.
- Parameters:
function_name (str)
args (Sequence[Expression])
kwargs (Mapping[str, Expression])
scope (Scope)
- Return type:
- fluent_codegen.codegen.method_call(obj, method_name, args, kwargs)[source]
Create a method call expression on obj.
- Parameters:
obj (Expression)
method_name (str)
args (Sequence[Expression])
kwargs (Mapping[str, Expression])
- 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.simplify(codegen_ast, simplifier)[source]
Repeatedly apply simplifier to codegen_ast until no more changes are made.
The simplifier function should return None if no changes are to be made, or the new CodeGenAst object otherwise.
- Parameters:
codegen_ast (CodeGenAst | CodeGenAstList)
simplifier (Callable[[CodeGenAst | CodeGenAstList], CodeGenAst | None])
- 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).
- fluent_codegen.codegen.morph_into(item, new_item)[source]
Mutate item in-place to behave identically to new_item while preserving identity.
- 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 = ymakesyunused, it will be removed too. RaisesAssertionErroron nested scopes.- Parameters:
func (Function)
- Return type:
None