Package: codenode-python
ContentsWhat is this?How do I install it?How do I use it?ExtensionsReferenceWhat is this?This module contains some helper classes and functions for generating
python code usingcodenode.How do I install it?From PyPI:pip install codenode-pythonFrom GitHub:pip install git+https://github.com/0xf0f/codenode-pythonHow do I use it?Helpers imported fromcodenode_pythoncan be used to describe python
code, and, like any other iterable, passed intocodenode.dump/dumpsto generate output.Compound statement nodes, which inherit fromcodenode_python.node.Node,
haveadd_childandadd_childrenmethods for adding inner nodes.
They also have conveniencedump/dumpsmethods to generate output
by calling codenode's defaultdump/dumpswith the node as an
argument.Simple example:importcodenodeascnimportcodenode_pythonaspyblock=[]foriinrange(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)ExtensionsNew compound statement nodes can be implemented by creating
subclasses ofcodenode_python.node.Node.ReferenceContentscodenode_python.node.Nodecodenode_python.Functioncodenode_python.Classcodenode_python.method.Methodcodenode_python.Ifcodenode_python.conditional.Elifcodenode_python.conditional.Elsecodenode_python.Forcodenode_python.Whilecodenode_python.Trycodenode_python.try_except.Exceptcodenode_python.try_except.Finallycodenode_python.Withcodenode_python.Matchcodenode_python.match_statement.Casecodenode_python.DocStringcodenode_python.Commentcodenode_python.commentedcodenode_python.node.NodeclassNode(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 methodEach node has an inherited convenience dump/dumps method.Overridable methods yielding nodes for three different innner
sections:headerbody (indented by default inPartitionedNode.__iter__)footerDocumentation for ParitionedNode can be viewedhere.Will output a single 'pass' line as its body section if no other
nodes are added as its children.codenode_python.FunctionclassFunction(Node):...Nodes representing a python function definition.Methods__init__classFunction(Node):def__init__(self,name:str,*args:str,**kwargs:str):...Parametersname:Name of function.args:Positional argument names of function.kwargs:Keyword argument names and values of function.add_decoratorclassFunction(Node):defadd_decorator(self,decorator:str):...Adds a decorator to this function definition.Parametersdecorator:Decorator to add.Attributesname: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.codenode_python.ClassclassClass(Node):...Nodes representing a python class definition.Methods__init__classClass(Node):def__init__(self,name,*parents):...Parametersname:Name of class.parents:Parent class names/add_decoratorclassClass(Node):defadd_decorator(self,decorator:str):...Adds a decorator to this class definition.Parametersdecorator:Decorator to add.add_methodclassClass(Node):defadd_method(self,name:str,*args:str,**kwargs:str)->Method:...Creates a method definition, adds it to this class definition's
body, then returns it.Parametersname:Name of method.args:Positional argument names of method.kwargs:Keyword argument names and values of method.ReturnsNew method.Attributesname: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.codenode_python.method.MethodclassMethod(Function):...Nodes representing a method definition.
Don't instantiate these directly, use the parent node's add_method
method instead.Methods__init__classMethod(Function):def__init__(self,name,*args:str,**kwargs:str):...Parametersname:Name of method.args:Positional argument names of method.kwargs:Keyword argument names and values of method.codenode_python.IfclassIf(Node):...Nodes representing a python if statement.Methods__init__classIf(Node):def__init__(self,condition:str):...Parameterscondition:Condition checked for by the if.add_elifclassIf(Node):defadd_elif(self,condition:str)->'Elif':...Create an Elif node, add it to this node's elifs,
then return it.Parameterscondition:Condition checked for by elif.ReturnsNew Elif node.add_elseclassIf(Node):defadd_else(self)->'Else':...Create an Else node, set it to this node's else node,
then return it.ReturnsNew Else nodeAttributescondition: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.codenode_python.conditional.ElifclassElif(Node):...Nodes representing a python elif statement.
Don't instantiate these directly, use If.add_elif instead.Methods__init__classElif(Node):def__init__(self,condition:str):...Parameterscondition:Condition check for by elif.Attributescondition:str -
Condition checked for by elif.codenode_python.conditional.ElseclassElse(Node):...Nodes representing a python else statement.
Don't instantiate these directly, use the parent node's add_else
method instead.codenode_python.ForclassFor(Node):...Nodes representing a python for loop.Methods__init__classFor(Node):def__init__(self,expression:str):...Parametersexpression:Expression iterated over by the for loop.add_elseclassFor(Node):defadd_else(self)->Else:...Create an Else node, set it to this node's else node,
then return it.ReturnsNew Else nodeAttributesexpression:str -
Expression iterated over by the for loop.else_node:Else -
Optional Else node following the for loop.codenode_python.WhileclassWhile(Node):...Nodes representing a python while loop statement.Methods__init__classWhile(Node):def__init__(self,condition:str):...Parameterscondition:The condition the while loop will check.add_elseclassWhile(Node):defadd_else(self):...Creates a new else node, sets it as this node's else node,
then returns it.ReturnsNew else node.Attributescondition:The condition the while loop will check.else_node:Optional[Else] -
Optional else node following this while statement node.codenode_python.TryclassTry(Node):...Nodes representing a python try statement.Methodsadd_exceptclassTry(Node):defadd_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.Parameterstypes: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.ReturnsNew except clause node.add_elseclassTry(Node):defadd_else(self)->Else:...Creates a new else node, sets it as this node's else node,
then returns it.ReturnsNew else node.add_finallyclassTry(Node):defadd_finally(self)->Finally:...Creates a new finally node, sets it as this node's finally node,
then returns it.ReturnsNew finally node.Attributesexcept_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.codenode_python.try_except.ExceptclassExcept(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.Methods__init__classExcept(Node):def__init__(self,types=(),name:Optional[str]=None,exception_group=False):...Parameterstypes: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.Attributestypes:'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.codenode_python.try_except.FinallyclassFinally(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.codenode_python.WithclassWith(Node):...Nodes representing a python with statement.Methods__init__classWith(Node):def__init__(self,*expressions:str):...Parametersexpressions:Expressions used within the context of the
with block.Attributesexpressions:'tuple[str]' -
Expressions used within the context of the with block.codenode_python.MatchclassMatch:...Nodes representing a python match statement.Methods__init__classMatch:def__init__(self,subject:str):...Parameterssubject:Subject of match statement.add_caseclassMatch:defadd_case(self,pattern:str)->Case:...Creates a new case node, adds it to this node's case node list,
then returns it.Parameterspattern:Pattern new case will match to.ReturnsNew case node.Attributessubject:str -
Subject of match statement.cases:'list[Case]' -
List of case block nodes belonging to this match statement.codenode_python.match_statement.CaseclassCase(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.Methods__init__classCase(Node):def__init__(self,pattern:str):...Parameterspattern:Pattern this case will match to.Attributespattern:str -
Pattern this case will match to.codenode_python.DocStringclassDocString:...Nodes representing a python docstring.Methods__init__classDocString:def__init__(self,content=''):...Parameterscontent:Content of docstring.
Will be broken down into separate lines.Attributescontent:Content of docstring.codenode_python.CommentclassComment:...Nodes representing a python comment.Methods__init__classComment:def__init__(self,content=''):...Parameterscontent:Comment content. Will be split into individual
lines.Attributescontent:Comment content.codenode_python.commenteddefcommented(node,dumps=lambdanode:codenode.dumps(node))->Comment:...Returns a comment node whose content is based on the string output
of processing another node.Parametersnode:Node whose string output will be used as the content
of the comment.dumps:Function used to convert the node to a string.ReturnsNew comment node.