This module contains some helper classes and functions for generating python code using codenode.
pip install codenode-python
pip install git+https://github.com/0xf0f/codenode-python
Helpers imported from codenode_python can be used to describe python
code, and, like any other iterable, passed into codenode.dump/dumps
to generate output.
Compound statement nodes, which inherit from codenode_python.node.Node,
have add_child and add_children methods for adding inner nodes.
They also have convenience dump/dumps methods to generate output
by calling codenode's default dump/dumps with the node as an
argument.
Simple example:
import codenode as cn
import codenode_python as py
block = []
for i in range(5):
func = py.Function(f'count_to_{i}')
count_loop = py.For(f'i in range({i})')
count_loop.add_child(py.Call('print', 'i'))
func.add_child(count_loop)
block.append(func)
block.append(cn.empty_lines(1))
print(cn.dumps(block))Which outputs:
def count_to_0():
for i in range(0):
print(i)
def count_to_1():
for i in range(1):
print(i)
def count_to_2():
for i in range(2):
print(i)
def count_to_3():
for i in range(3):
print(i)
def count_to_4():
for i in range(4):
print(i)
New compound statement nodes can be implemented by creating
subclasses of codenode_python.node.Node.
- codenode_python.node.Node
- codenode_python.Function
- codenode_python.Class
- codenode_python.method.Method
- codenode_python.If
- codenode_python.conditional.Elif
- codenode_python.conditional.Else
- codenode_python.For
- codenode_python.While
- codenode_python.Try
- codenode_python.try_except.Except
- codenode_python.try_except.Finally
- codenode_python.With
- codenode_python.Match
- codenode_python.match_statement.Case
- codenode_python.DocString
- codenode_python.Comment
- codenode_python.commented
class Node(codenode_utilities.PartitionedNode): ...Nodes that can contain an arbitrary number of inner python statements.
Due to inheriting from PartitionedNode:
- Each node has a list of children nodes, along with a add_child and add_children method
- Each node has an inherited convenience dump/dumps method.
- Overridable methods yielding nodes for three different innner sections:
- header
- body (indented by default in
PartitionedNode.__iter__)- footer
Documentation for ParitionedNode can be viewed here.
Will output a single 'pass' line as its body section if no other nodes are added as its children.
class Function(Node): ...Nodes representing a python function definition.
class Function(Node): def __init__(self, name: str, *args: str, **kwargs: str): ...
name: Name of function.
args: Positional argument names of function.
kwargs: Keyword argument names and values of function.
class Function(Node): def add_decorator(self, decorator: str): ...Adds a decorator to this function definition.
decorator: Decorator to add.
name: str - Name of function.
args: 'tuple[str]' - Tuple of positional argument names of function.
kwargs: 'dict[str, str]' - Keyword argument names and values of function.
decorators: 'list[str]' - List of decorators applied to this function definition, each one a single string.
return_type: Optional[str] - Return type annotation of function.
class Class(Node): ...Nodes representing a python class definition.
class Class(Node): def __init__(self, name, *parents): ...
name: Name of class.
parents: Parent class names/
class Class(Node): def add_decorator(self, decorator: str): ...Adds a decorator to this class definition.
decorator: Decorator to add.
class Class(Node): def add_method(self, name: str, *args: str, **kwargs: str) -> Method: ...Creates a method definition, adds it to this class definition's body, then returns it.
name: Name of method.
args: Positional argument names of method.
kwargs: Keyword argument names and values of method.
New method.
name: str - Name of class.
parents: 'tuple[str]' - Tuple of parent class names.
decorators: 'list[str]' - List of decorators applied to this class definition, each one a single string.
class Method(Function): ...Nodes representing a method definition. Don't instantiate these directly, use the parent node's add_method method instead.
class Method(Function): def __init__(self, name, *args: str, **kwargs: str): ...
name: Name of method.
args: Positional argument names of method.
kwargs: Keyword argument names and values of method.
class If(Node): ...Nodes representing a python if statement.
class If(Node): def __init__(self, condition: str): ...
condition: Condition checked for by the if.
class If(Node): def add_elif(self, condition: str) -> 'Elif': ...Create an Elif node, add it to this node's elifs, then return it.
condition: Condition checked for by elif.
New Elif node.
class If(Node): def add_else(self) -> 'Else': ...Create an Else node, set it to this node's else node, then return it.
New Else node
condition: str - Condition checked for by the if.
elif_nodes: 'list[Elif]' - List of Elif nodes following the if check.
else_node: Optional[Else] - Optional Else node following the if check and its elifs.
class Elif(Node): ...Nodes representing a python elif statement. Don't instantiate these directly, use If.add_elif instead.
class Elif(Node): def __init__(self, condition: str): ...
condition: Condition check for by elif.
condition: str - Condition checked for by elif.
class Else(Node): ...Nodes representing a python else statement. Don't instantiate these directly, use the parent node's add_else method instead.
class For(Node): ...Nodes representing a python for loop.
class For(Node): def __init__(self, expression: str): ...
expression: Expression iterated over by the for loop.
class For(Node): def add_else(self) -> Else: ...Create an Else node, set it to this node's else node, then return it.
New Else node
expression: str - Expression iterated over by the for loop.
else_node: Else - Optional Else node following the for loop.
class While(Node): ...Nodes representing a python while loop statement.
class While(Node): def __init__(self, condition: str): ...
condition: The condition the while loop will check.
class While(Node): def add_else(self): ...Creates a new else node, sets it as this node's else node, then returns it.
New else node.
condition: The condition the while loop will check.
else_node: Optional[Else] - Optional else node following this while statement node.
class Try(Node): ...Nodes representing a python try statement.
class Try(Node): def add_except(self, types: 'tuple[str, ...]'=(), name: Optional[str]=None, exception_group=False) -> Except: ...Creates a new except clause node, adds it to this node's list of except nodes, then returns it.
types: Exception types this clause catches.
name: Named assigned to caught exception.
exception_group: If true, exception clause is treated as an exception group extraction clause instead.
New except clause node.
class Try(Node): def add_else(self) -> Else: ...Creates a new else node, sets it as this node's else node, then returns it.
New else node.
class Try(Node): def add_finally(self) -> Finally: ...Creates a new finally node, sets it as this node's finally node, then returns it.
New finally node.
except_nodes: 'list[Except]' - List of except nodes following this try statement node.
finally_node: Optional[Finally] - Optional finally clause node following this try statement node.
else_node: Optional[Else] - Optional else node following this try statement node.
class Except(Node): ...Nodes representing an except block following a python try block. Don't instantiate these directly, use the parent method's add_except method instead.
class Except(Node): def __init__(self, types=(), name: Optional[str]=None, exception_group=False): ...
types: Exception types this clause catches.
name: Named assigned to caught exception.
exception_group: If true, exception clause is treated as an exception group extraction clause instead.
types: 'tuple[str, ...]' - Exception types this clause catches.
name: Optional[str] - Named assigned to caught exception.
exception_group: bool - If true, exception clause is treated as an exception group extraction clause instead.
class Finally(Node): ...Node representing a finally clause following a python try statement. Don't instantiate these directly, use the parent node's add_finally method instead.
class With(Node): ...Nodes representing a python with statement.
class With(Node): def __init__(self, *expressions: str): ...
expressions: Expressions used within the context of the with block.
expressions: 'tuple[str]' - Expressions used within the context of the with block.
class Match: ...Nodes representing a python match statement.
class Match: def __init__(self, subject: str): ...
subject: Subject of match statement.
class Match: def add_case(self, pattern: str) -> Case: ...Creates a new case node, adds it to this node's case node list, then returns it.
pattern: Pattern new case will match to.
New case node.
subject: str - Subject of match statement.
cases: 'list[Case]' - List of case block nodes belonging to this match statement.
class Case(Node): ...Nodes representing a case block in a python match statement. Don't instantiate these directly, use the parent node's add_case method instead.
class Case(Node): def __init__(self, pattern: str): ...
pattern: Pattern this case will match to.
pattern: str - Pattern this case will match to.
class DocString: ...Nodes representing a python docstring.
class DocString: def __init__(self, content=''): ...
content: Content of docstring. Will be broken down into separate lines.
content: Content of docstring.
class Comment: ...Nodes representing a python comment.
class Comment: def __init__(self, content=''): ...
content: Comment content. Will be split into individual lines.
content: Comment content.
def commented(node, dumps=lambda node: codenode.dumps(node)) -> Comment: ...Returns a comment node whose content is based on the string output of processing another node.
node: Node whose string output will be used as the content of the comment.
dumps: Function used to convert the node to a string.
New comment node.