This is the reference page for every node type encountered in RedBaron and their specificities.

Nodes References Page

TopClass

CodeBlockNode

CodeBlockNode is a type of node that has a body composed of indented code like the DefNode or the IfNode. Great care has been taken on the SetAttr of their value so you don’t have to take care about reindenting and other formatting details.

Demonstration:

In [1]: red = RedBaron("def function():\n    pass\n")

In [2]: red
Out[2]: 
0   def function():
        pass
    

In [3]: red[0].value = "stuff"  # first '\n' will be added, indentation will be set

In [4]: red
Out[4]: 
0   def function():
        stuff
    

In [5]: red[0].value = "                    bad_indent"

In [6]: red
Out[6]: 
0   def function():
        bad_indent
    

In [7]: red[0].value = " some\n stuff"

In [8]: red
Out[8]: 
0   def function():
        some
        stuff

Some for indented cases:

In [9]: red = RedBaron("class A:\n    def __init__():\n        pass\n\n    def plop():\n        pass")

In [10]: red.def_.value = "not_indented"

In [11]: red
Out[11]: 
0   class A:
        def __init__():
            not_indented
    
        def plop():
            pass
    

In [12]: red.def_.value = "\n                              badly_indented"

In [13]: red
Out[13]: 
0   class A:
        def __init__():
            badly_indented
    
        def plop():
            pass
    

In [14]: red.def_.value = "some\nstuff\nfoo\nbar\n\npouet"

In [15]: red
Out[15]: 
0   class A:
        def __init__():
            some
            stuff
            foo
            bar
        
            pouet
    
        def plop():
            pass

Nodes

ArgumentGeneratorComprehensionNode

A node representing generator passed as an argument during a function call.

In [16]: RedBaron("a(x for y in z)")[0].value[1].value[0].help(deep=True)
ArgumentGeneratorComprehensionNode()
  # identifiers: argument_generator_comprehension, argument_generator_comprehension_, argumentgeneratorcomprehension, argumentgeneratorcomprehensionnode
  result ->
    NameNode()
      # identifiers: name, name_, namenode
      value='x'
  generators ->
    * ComprehensionLoopNode()
        # identifiers: comprehension_loop, comprehension_loop_, comprehensionloop, comprehensionloopnode
        iterator ->
          NameNode()
            # identifiers: name, name_, namenode
            value='y'
        target ->
          NameNode()
            # identifiers: name, name_, namenode
            value='z'
        ifs ->

SetAttr

In [17]: red = RedBaron("a(x for y in z)")

In [18]: red
Out[18]: 0   a(x for y in z)

In [19]: red[0].value[1].value[0].result = "pouet"

In [20]: red
Out[20]: 0   a(pouet for y in z)

In [21]: red[0].value[1].value[0].generators = "for artichaut in courgette"

In [22]: red
Out[22]: 0   a(pouet for artichaut in courgette)

AssertNode

A node representing the assert statement.

In [23]: RedBaron("assert test, message")[0].help(deep=True)
AssertNode()
  # identifiers: assert, assert_, assertnode
  value ->
    NameNode()
      # identifiers: name, name_, namenode
      value='test'
  message ->
    NameNode()
      # identifiers: name, name_, namenode
      value='message'

SetAttr

In [24]: red = RedBaron("assert some_test")

In [25]: red
Out[25]: 0   assert some_test

In [26]: red[0].value = "1 == caramba()"

In [27]: red
Out[27]: 0   assert 1 == caramba()

In [28]: red[0].message = "'foo bar'"

In [29]: red
Out[29]: 0   assert 1 == caramba(), 'foo bar'

In [30]: red[0].message = ""

In [31]: red
Out[31]: 0   assert 1 == caramba()

AssignmentNode

A node representing the assign operation in python (foo = bar) and the “augmented” assign (foo += bar).

In [32]: RedBaron("a = b")[0].help(deep=True)
AssignmentNode()
  # identifiers: assign, assignment, assignment_, assignmentnode
  operator=''
  target ->
    NameNode()
      # identifiers: name, name_, namenode
      value='a'
  value ->
    NameNode()
      # identifiers: name, name_, namenode
      value='b'

In [33]: RedBaron("a += b")[0].help(deep=True)
AssignmentNode()
  # identifiers: assign, assignment, assignment_, assignmentnode
  operator='+'
  target ->
    NameNode()
      # identifiers: name, name_, namenode
      value='a'
  value ->
    NameNode()
      # identifiers: name, name_, namenode
      value='b'

SetAttr

Works as expected:

In [34]: red = RedBaron("a = b")

In [35]: red[0].first = "caramba"

In [36]: red
Out[36]: 0   a = b

In [37]: red[0].second = "42"

In [38]: red
Out[38]: 0   a = b

For the operator part, expected input should work:

In [39]: red = RedBaron("a = b")

In [40]: red[0].operator = "+="

In [41]: red
Out[41]: 0   a += b

In [42]: red[0].operator = "+" # equivalent to '+='

In [43]: red
Out[43]: 0   a += b

In [44]: red[0].operator = "-" # equivalent to '-='

In [45]: red
Out[45]: 0   a -= b

In [46]: red[0].operator = "=" # equivalent to '='

In [47]: red
Out[47]: 0   a = b

In [48]: red[0].operator = "/="

In [49]: red
Out[49]: 0   a /= b

In [50]: red[0].operator = "" # equivalent to '='

In [51]: red
Out[51]: 0   a = b

AssociativeParenthesisNode

This node represents a statement prioritised on another by being surrounded by parenthesis. For e.g., the first part of this addition: (1 + 1) * 2.

In [52]: RedBaron("(foo)")[0].help(deep=True)
AssociativeParenthesisNode()
  # identifiers: associative_parenthesis, associative_parenthesis_, associativeparenthesis, associativeparenthesisnode
  value ->
    NameNode()
      # identifiers: name, name_, namenode
      value='foo'

SetAttr

In [53]: red = RedBaron("(foo)")

In [54]: red
Out[54]: 0   (foo)

In [55]: red[0].value = "1 + 1"

In [56]: red
Out[56]: 0   (1 + 1)

AtomtrailersNode

This node represents a combination of NameNode, DotNode, CallNode, GetitemNode sorted in a list. For e.g.: a.b().c[d].

In [57]: RedBaron("a.b().c[d]")[0].help(deep=True)
AtomtrailersNode()
  # identifiers: atomtrailers, atomtrailers_, atomtrailersnode
  value ->
    * NameNode()
        # identifiers: name, name_, namenode
        value='a'
    * NameNode()
        # identifiers: name, name_, namenode
        value='b'
    * CallNode()
        # identifiers: call, call_, callnode
        value ->
    * NameNode()
        # identifiers: name, name_, namenode
        value='c'
    * GetitemNode()
        # identifiers: getitem, getitem_, getitemnode
        value ->
          NameNode()
            # identifiers: name, name_, namenode
            value='d'

SetAttr

In [58]: red = RedBaron("a.b()")

In [59]: red
Out[59]: 0   a.b()

In [60]: red[0].value = "d.be"

In [61]: red
Out[61]: 0   d.be

BinaryNode

The node represents a binary number value.

In [62]: RedBaron("0b10101")[0].help(deep=True)
BinaryNode()
  # identifiers: binary, binary_, binarynode
  value='0b10101'

BinaryOperatorNode

The node represents a binary operator (an operator (e.g.: + - /..) applied to 2 values) with its operands. For e.g.: 1 + 1.

In [63]: RedBaron("1 + 1")[0].help(deep=True)
BinaryOperatorNode()
  # identifiers: binary_operator, binary_operator_, binaryoperator, binaryoperatornode
  value='+'
  first ->
    IntNode()
      # identifiers: int, int_, intnode
      value='1'
  second ->
    IntNode()
      # identifiers: int, int_, intnode
      value='1'

SetAttr

In [64]: red = RedBaron("1 + 1")

In [65]: red
Out[65]: 0   1 + 1

In [66]: red[0].value = "*"

In [67]: red
Out[67]: 0   1 * 1

In [68]: red[0].first = "(1 + 1)"

In [69]: red
Out[69]: 0   (1 + 1) * 1

In [70]: red[0].second = "caramba"

In [71]: red
Out[71]: 0   (1 + 1) * caramba

BooleanOperatorNode

The node represents a boolean operator (an operator (e.g.: and or) applied to 2 values) with its operands. For e.g.: x and y.

In [72]: RedBaron("x and y")[0].help(deep=True)
BooleanOperatorNode()
  # identifiers: boolean_operator, boolean_operator_, booleanoperator, booleanoperatornode
  value='and'
  first ->
    NameNode()
      # identifiers: name, name_, namenode
      value='x'
  second ->
    NameNode()
      # identifiers: name, name_, namenode
      value='y'

SetAttr

In [73]: red = RedBaron("x and y")

In [74]: red
Out[74]: 0   x and y

In [75]: red[0].value = "or"

In [76]: red
Out[76]: 0   x or y

In [77]: red[0].first = "plop"

In [78]: red
Out[78]: 0   plop or y

In [79]: red[0].second = "oupsi"

In [80]: red
Out[80]: 0   plop or oupsi

CallNode

A node representing a call (eg: a(), here a is called with no arguments). It is always stored in an AtomtrailersNode or a DecoratorNode.

In [81]: RedBaron("a(b, c=d)")[0].value[1].help(deep=True)
CallNode()
  # identifiers: call, call_, callnode
  value ->
    * CallArgumentNode()
        # identifiers: call_argument, call_argument_, callargument, callargumentnode
        target ->
          None
        value ->
          NameNode()
            # identifiers: name, name_, namenode
            value='b'
    * CallArgumentNode()
        # identifiers: call_argument, call_argument_, callargument, callargumentnode
        target ->
          NameNode()
            # identifiers: name, name_, namenode
            value='c'
        value ->
          NameNode()
            # identifiers: name, name_, namenode
            value='d'

SetAttr

SetAttr works as expected:

In [82]: red = RedBaron("a()")

In [83]: red[0].value[1].value = "b, c=d, *e, **f"

In [84]: red
Out[84]: 0   a(b, c=d, *e, **f)

CallArgumentNode

A node representing an argument or a named argument of a CallNode (other nodes that can be in a CallNode are ListArgumentNode and DictArgumentNode).

In [85]: RedBaron("a(b, c=d)")[0].value[1].value[0].help(deep=True)
CallArgumentNode()
  # identifiers: call_argument, call_argument_, callargument, callargumentnode
  target ->
    None
  value ->
    NameNode()
      # identifiers: name, name_, namenode
      value='b'

In [86]: RedBaron("a(b, c=d)")[0].value[1].value[1].help(deep=True)
CallArgumentNode()
  # identifiers: call_argument, call_argument_, callargument, callargumentnode
  target ->
    NameNode()
      # identifiers: name, name_, namenode
      value='c'
  value ->
    NameNode()
      # identifiers: name, name_, namenode
      value='d'

SetAttr

In [87]: red = RedBaron("a(b)")

In [88]: red
Out[88]: 0   a(b)

In [89]: red[0].value[1].value[0] = "stuff=foo"

In [90]: red
Out[90]: 0   a(stuff=foo)

ClassNode

A node representing a class definition.

In [91]: RedBaron("class SomeAwesomeName(A, B, C): pass")[0].help(deep=True)
ClassNode()
  # identifiers: class, class_, classnode
  # default test value: name
  name='SomeAwesomeName'
  parenthesis=True
  decorators ->
  inherit_from ->
    * TupleNode()
        # identifiers: tuple, tuple_, tuplenode
        with_parenthesis=False
        value ->
          * NameNode()
              # identifiers: name, name_, namenode
              value='A'
          * NameNode()
              # identifiers: name, name_, namenode
              value='B'
          * NameNode()
              # identifiers: name, name_, namenode
              value='C'
  value ->
    * PassNode()
        # identifiers: pass, pass_, passnode

SetAttr

ClassNode is a CodeBlockNode which means its value attribute accepts a wide range of values, see CodeBlockNode for more information. Most other attributes work as expected:

In [92]: red = RedBaron("class SomeAwesomeName(A, B, C): pass")

In [93]: red[0].name = "AnotherAwesomeName"

In [94]: red
Out[94]: 
0   class AnotherAwesomeName(A, B, C): pass
    

In [95]: red[0].inherit_from = "object"

In [96]: red
Out[96]: 
0   class AnotherAwesomeName(object): pass

CommaNode

A node representing a comma, this is the kind of formatting node that you might have to deal with if not enough high level helpers are available. They are generally present in call, function arguments definition and data structure sugar syntactic notation.

The comma node is responsible for holding the formatting around it.

In [97]: RedBaron("[1, 2, 3]")[0].value.node_list[1].help(deep=True)
CommaNode()
  # identifiers: comma, comma_, commanode

ComparisonNode

The node represents a comparison operation, for e.g.: 42 > 30.

In [98]: RedBaron("42 > 30")[0].help(deep=True)
ComparisonNode()
  # identifiers: comparison, comparison_, comparisonnode
  first ->
    IntNode()
      # identifiers: int, int_, intnode
      value='42'
  value ->
    ComparisonOperatorNode()
      # identifiers: comparison_operator, comparison_operator_, comparisonoperator, comparisonoperatornode
      first='>'
      second=''
  second ->
    IntNode()
      # identifiers: int, int_, intnode
      value='30'

SetAttr

In [99]: red = RedBaron("42 > 30")

In [100]: red
Out[100]: 0   42 > 30

In [101]: red[0].operator = "=="

In [102]: red
Out[102]: 0   42 > 30

In [103]: red[0].first = "(1 + 1)"

In [104]: red
Out[104]: 0   (1 + 1) > 30

In [105]: red[0].second = "caramba"

In [106]: red
Out[106]: 0   (1 + 1) > caramba

ComprehensionIfNode

The node represents “if” condition in a comprehension loop. It is always a member of a ComprehensionLoopNode.

In [107]: RedBaron("[x for x in x if condition]")[0].generators[0].ifs[0].help(deep=True)
ComprehensionIfNode()
  # identifiers: comprehension_if, comprehension_if_, comprehensionif, comprehensionifnode
  value ->
    NameNode()
      # identifiers: name, name_, namenode
      value='condition'

SetAttr

In [108]: red = RedBaron("[x for x in x if condition]")

In [109]: red
Out[109]: 0   [x for x in x if condition]

In [110]: red[0].generators[0].ifs[0].value = "True"

In [111]: red
Out[111]: 0   [x for x in x if True]

ComprehensionLoopNode

The node represents the loop part of a comprehension structure.

In [112]: RedBaron("[x for y in z]")[0].generators[0].help(deep=True)
ComprehensionLoopNode()
  # identifiers: comprehension_loop, comprehension_loop_, comprehensionloop, comprehensionloopnode
  iterator ->
    NameNode()
      # identifiers: name, name_, namenode
      value='y'
  target ->
    NameNode()
      # identifiers: name, name_, namenode
      value='z'
  ifs ->

SetAttr

In [113]: red = RedBaron("[x for y in z]")

In [114]: red
Out[114]: 0   [x for y in z]

In [115]: red[0].generators[0].target = "plop"

In [116]: red
Out[116]: 0   [x for y in plop]

In [117]: red[0].generators[0].iterator = "iter"

In [118]: red
Out[118]: 0   [x for iter in plop]

In [119]: red[0].generators[0].ifs = "if a if b"

In [120]: red
Out[120]: 0   [x for iter in plop if a if b]

DecoratorNode

A node representing an individual decorator (of a function or a class).

In [121]: RedBaron("@stuff.plop(*a)\ndef b(): pass")[0].decorators[0].help(deep=True)
DecoratorNode()
  # identifiers: decorator, decorator_, decoratornode
  value ->
    DottedNameNode()
      # identifiers: dotted_name, dotted_name_, dottedname, dottednamenode
      value ->
        * NameNode()
            # identifiers: name, name_, namenode
            value='stuff'
        * DotNode()
            # identifiers: dot, dot_, dotnode
        * NameNode()
            # identifiers: name, name_, namenode
            value='plop'
  call ->
    CallNode()
      # identifiers: call, call_, callnode
      value ->
        * ListArgumentNode()
            # identifiers: list_argument, list_argument_, listargument, listargumentnode
            value ->
              NameNode()
                # identifiers: name, name_, namenode
                value='a'

SetAttr

In [122]: red = RedBaron("@stuff\ndef a(): pass")

In [123]: red
Out[123]: 
0   @stuff
    def a(): pass
    

In [124]: red[0].decorators[0].value = "a.b.c"

In [125]: red
Out[125]: 
0   @a.b.c
    def a(): pass
    

In [126]: red[0].decorators[0].call = "(*args)"

In [127]: red
Out[127]: 
0   @a.b.c(*args)
    def a(): pass
    

In [128]: red[0].decorators[0].call = ""

In [129]: red
Out[129]: 
0   @a.b.c
    def a(): pass

DefNode

A node representing a function definition.

In [130]: RedBaron("def stuff():\n    pass\n")[0].help(deep=True)
DefNode()
  # identifiers: def, def_, defnode, funcdef, funcdef_
  # default test value: name
  async=False
  name='stuff'
  decorators ->
  arguments ->
  value ->
    * PassNode()
        # identifiers: pass, pass_, passnode

SetAttr

DefNode is a CodeBlockNode which means its value attribute accepts a wide range of values, see CodeBlockNode for more information. Most other attributes works as expected:

In [131]: red = RedBaron("def stuff():\n    body\n")

In [132]: red[0]
Out[132]: 
def stuff():
    body

In [133]: red[0].name = "awesome_function"

In [134]: red[0].arguments = "a, b=None, *c, **d"

In [135]: red
Out[135]: 
0   def awesome_function(a, b=None, *c, **d):
        body

Decorators might be a bit less intuitive:

In [136]: red =  RedBaron("def stuff():\n    body\n")

In [137]: red[0].decorators = "@foo(*plop)"

In [138]: red
Out[138]: 
0   @foo(*plop)
    def stuff():
        body
    

In [139]: red[0].decorators = "@foo\n@bar.baz()"

In [140]: red
Out[140]: 
0   @foo
    @bar.baz()
    def stuff():
        body
    

In [141]: red[0].decorators = "    @pouet"  # SetAttr will take care of reindenting everything as expected

In [142]: red
Out[142]: 
0   @pouet
    def stuff():
        body

New in 0.7.

Async is a boolean attribute that determine if a function is async:

In [143]: red =  RedBaron("def stuff():\n    body\n")

In [144]: red[0].async_
Out[144]: False

In [145]: red[0].async_ = True

In [146]: red
Out[146]: 
0   async def stuff():
        body
    

In [147]: red[0].async_ = False

In [148]: red
Out[148]: 
0   def stuff():
        body

Warning

As of python 3.7 async and await are now reserved keywords so don’t uses red.async, it works as expected but won’t make your code forward compatible.

DefArgumentNode

A node representing an argument in a function definition.

In [149]: RedBaron("def a(b, c=d): pass")[0].arguments.help(deep=True)
0 -----------------------------------------------------
DefArgumentNode()
  # identifiers: def_argument, def_argument_, defargument, defargumentnode
  target ->
    NameNode()
      # identifiers: name, name_, namenode
      value='b'
  value ->
    None
1 -----------------------------------------------------
CommaNode()
  # identifiers: comma, comma_, commanode
2 -----------------------------------------------------
DefArgumentNode()
  # identifiers: def_argument, def_argument_, defargument, defargumentnode
  target ->
    NameNode()
      # identifiers: name, name_, namenode
      value='c'
  value ->
    NameNode()
      # identifiers: name, name_, namenode
      value='d'

SetAttr

In [150]: red = RedBaron("def a(b): pass")

In [151]: red
Out[151]: 
0   def a(b): pass
    

In [152]: red[0].arguments[0].name = "plop"

In [153]: red
Out[153]: 
0   def a(b): pass
    

In [154]: red[0].arguments[0].value = "1 + 1"

In [155]: red
Out[155]: 
0   def a(b=1 + 1): pass

DelNode

A node representing a del statement.

In [156]: RedBaron("del stuff")[0].help(deep=True)
DelNode()
  # identifiers: del, del_, delnode
  value ->
    NameNode()
      # identifiers: name, name_, namenode
      value='stuff'

SetAttr

In [157]: red = RedBaron("del stuff")

In [158]: red
Out[158]: 0   del stuff

In [159]: red[0].value = "some, other, stuff"

In [160]: red
Out[160]: 0   del some, other, stuff

DictArgumentNode

A node representing a ‘kwargs’ defined in a function definition argument or used in a CallNode.

In [161]: RedBaron("a(**b)")[0].value[1].value[0].help(deep=True)
DictArgumentNode()
  # identifiers: dict_argument, dict_argument_, dictargument, dictargumentnode
  value ->
    NameNode()
      # identifiers: name, name_, namenode
      value='b'

SetAttr

In [162]: red = RedBaron("a(**b)")

In [163]: red
Out[163]: 0   a(**b)

In [164]: red[0].value[1].value[0].value = "plop"

In [165]: red
Out[165]: 0   a(**plop)

DictNode

A node representing python sugar syntactic notation for dict.

In [166]: RedBaron("{'a': 1, 'b': 2, 'c': 3}")[0].help(deep=True)
DictNode()
  # identifiers: dict, dict_, dictnode
  value ->
    * DictitemNode()
        # identifiers: dictitem, dictitem_, dictitemnode
        key ->
          StringNode()
            # identifiers: string, string_, stringnode
            value="'a'"
        value ->
          IntNode()
            # identifiers: int, int_, intnode
            value='1'
    * DictitemNode()
        # identifiers: dictitem, dictitem_, dictitemnode
        key ->
          StringNode()
            # identifiers: string, string_, stringnode
            value="'b'"
        value ->
          IntNode()
            # identifiers: int, int_, intnode
            value='2'
    * DictitemNode()
        # identifiers: dictitem, dictitem_, dictitemnode
        key ->
          StringNode()
            # identifiers: string, string_, stringnode
            value="'c'"
        value ->
          IntNode()
            # identifiers: int, int_, intnode
            value='3'

DictComprehensionNode

A node representing dictionary comprehension node.

In [167]: RedBaron("{a: b for c in d}")[0].help(deep=True)
DictComprehensionNode()
  # identifiers: dict_comprehension, dict_comprehension_, dictcomprehension, dictcomprehensionnode
  result ->
    DictitemNode()
      # identifiers: dictitem, dictitem_, dictitemnode
      key ->
        NameNode()
          # identifiers: name, name_, namenode
          value='a'
      value ->
        NameNode()
          # identifiers: name, name_, namenode
          value='b'
  generators ->
    * ComprehensionLoopNode()
        # identifiers: comprehension_loop, comprehension_loop_, comprehensionloop, comprehensionloopnode
        iterator ->
          NameNode()
            # identifiers: name, name_, namenode
            value='c'
        target ->
          NameNode()
            # identifiers: name, name_, namenode
            value='d'
        ifs ->

SetAttr

In [168]: red = RedBaron("{a: b for c in d}")

In [169]: red
Out[169]: 0   {a: b for c in d}

In [170]: red[0].result = "plop: poulpe"

In [171]: red
Out[171]: 0   {plop: poulpe for c in d}

In [172]: red[0].generators = "for zomg in wtf"

In [173]: red
Out[173]: 0   {plop: poulpe for zomg in wtf}

DottedAsNameNode

A node representing an argument to the import node.

In [174]: RedBaron("import a.b.c as d")[0].value[0].help(deep=True)
DottedAsNameNode()
  # identifiers: dotted_as_name, dotted_as_name_, dottedasname, dottedasnamenode
  target='d'
  value ->
    * NameNode()
        # identifiers: name, name_, namenode
        value='a'
    * NameNode()
        # identifiers: name, name_, namenode
        value='b'
    * NameNode()
        # identifiers: name, name_, namenode
        value='c'

SetAttr

In [175]: red = RedBaron("import a.b.c as d")

In [176]: red
Out[176]: 0   import a.b.c as d

In [177]: red[0].value[0].value = "some.random.module"

In [178]: red
Out[178]: 0   import some.random.module as d

In [179]: red[0].value[0].target = "stuff"

In [180]: red
Out[180]: 0   import some.random.module as stuff

DotNode

A node representing a dot ‘.’, generally found in atom trailers (this kind of structure: ‘variable.another_variable(call)[getitem]’). This is the kind of formatting node that you might have to deal with if not enough high level helpers are available.

The dot node is responsible for holding the formatting around it.

In [181]: RedBaron("a.b")[0].value[1].help(deep=True)
NameNode()
  # identifiers: name, name_, namenode
  value='b'

ElifNode

A node representing an elif statement.

The ElifNode, like the IfNode or the ElseNode are stored in a IfelseblockNode.

In [182]: RedBaron("if a: pass\nelif b: pass")[0].value[1].help(deep=True)
ElifNode()
  # identifiers: elif, elif_, elifnode
  test ->
    NameNode()
      # identifiers: name, name_, namenode
      value='b'
  value ->
    * PassNode()
        # identifiers: pass, pass_, passnode

SetAttr

ElifNode is a CodeBlockNode which means its value attribute accepts a wide range of values, see CodeBlockNode for more information. Other attributes work as expected:

In [183]: red = RedBaron("if a: pass\nelif b: pass")

In [184]: red
Out[184]: 
0   if a: pass
    elif b: pass
    

In [185]: red[0].value[1].test = "1 + 1 == 11"

In [186]: red
Out[186]: 
0   if a: pass
    elif 1 + 1 == 11: pass

ElseNode

A node representing an else statement.

The ElseNode, like the IfNode or the ElifNode, is stored in a IfelseblockNode.

In [187]: RedBaron("if a: pass\nelse: pass")[0].value[1].help(deep=True)
ElseNode()
  # identifiers: else, else_, elsenode
  value ->
    * PassNode()
        # identifiers: pass, pass_, passnode

SetAttr

ElifNode is a CodeBlockNode which means its value attribute accepts a wide range of values, see CodeBlockNode for more information.

EllipsisNode

A node representing “…”.

In [188]: RedBaron("def a(): ...").ellipsis.help(deep=True)
EllipsisNode()
  # identifiers: ellipsis, ellipsis_, ellipsisnode

EndlNode

A node for the end line (‘n’, ‘rn’) component.

This node is responsible for holding the indentation AFTER itself. This node also handles formatting around it, CommentNode before an EndlNode will end up in the formatting key of an EndlNode 99% of the time (the exception is if the CommentNode is the last node of the file).

In [189]: RedBaron("\n")[0].help()
EndlNode()
  # identifiers: endl, endl_, endlnode
  value='\n'
  indent=''

In [190]: RedBaron("# first node of the file\n# last node of the file").node_list.help()
0 -----------------------------------------------------
CommentNode()
  # identifiers: comment, comment_, commentnode
  value='# first node of the file'
1 -----------------------------------------------------
EndlNode()
  # identifiers: endl, endl_, endlnode
  value='\n'
  indent=''
2 -----------------------------------------------------
CommentNode()
  # identifiers: comment, comment_, commentnode
  value='# last node of the file'

ExceptNode

A node representing an except statement (member of a TryNode).

In [191]: RedBaron("try: pass\nexcept FooBar: pass\nexcept Exception: pass\nelse: pass\nfinally: pass\n")[0].excepts[0].help(deep=True)
ExceptNode()
  # identifiers: except, except_, exceptnode
  delimiter=''
  exception ->
    NameNode()
      # identifiers: name, name_, namenode
      value='FooBar'
  target ->
    None
  value ->
    * PassNode()
        # identifiers: pass, pass_, passnode

SetAttr

ExceptNode is a CodeBlockNode which means its value attribute accepts a wide range of values, see CodeBlockNode for more information. Other attributes work as expected:

In [192]: red = RedBaron("try: pass\nexcept: pass")

In [193]: red
Out[193]: 
0   try: pass
    except: pass
    

In [194]: red[0].excepts[0].exception = "plop"

In [195]: red
Out[195]: 
0   try: pass
    except plop: pass
    

In [196]: red[0].excepts[0].target = "stuff"

In [197]: red
Out[197]: 
0   try: pass
    except plop as stuff: pass
    

In [198]: red[0].excepts[0].exception = ""

In [199]: red
Out[199]: 
0   try: pass
    except: pass
    

# red[0].excepts[0].target = "stuff" <- would raise without a target

ExecNode

A node representing an exec statement.

In [200]: RedBaron("exec '1 + 1' in a, b")[0].help(deep=True)
ExecNode()
  # identifiers: exec, exec_, execnode
  value ->
    StringNode()
      # identifiers: string, string_, stringnode
      value="'1 + 1'"
  globals ->
    NameNode()
      # identifiers: name, name_, namenode
      value='a'
  locals ->
    NameNode()
      # identifiers: name, name_, namenode
      value='b'

SetAttr

In [201]: red = RedBaron("exec 'stuff'")

In [202]: red
Out[202]: 0   exec 'stuff'

In [203]: red[0].value = 'some_code'

In [204]: red
Out[204]: 0   exec some_code

In [205]: red[0].globals = 'x'

In [206]: red
Out[206]: 0   exec some_code in x

In [207]: red[0].locals = 'y'

In [208]: red
Out[208]: 0   exec some_code in x, y

FinallyNode

A node representing a finally statement (member of a TryNode).

In [209]: RedBaron("try: pass\nexcept FooBar: pass\nexcept Exception: pass\nelse: pass\nfinally: pass\n").finally_.help(deep=True)
FinallyNode()
  # identifiers: finally, finally_, finallynode
  value ->
    * PassNode()
        # identifiers: pass, pass_, passnode

SetAttr

FinallyNode is a CodeBlockNode which means its value attribute accepts a wide range of values, see CodeBlockNode for more information.

ForNode

A node representing a for loop.

In [210]: RedBaron("for i in b:\n    pass")[0].help(deep=True)
ForNode()
  # identifiers: for, for_, fornode
  async=False
  iterator ->
    NameNode()
      # identifiers: name, name_, namenode
      value='i'
  target ->
    NameNode()
      # identifiers: name, name_, namenode
      value='b'
  else ->
    None
  value ->
    * PassNode()
        # identifiers: pass, pass_, passnode

SetAttr

ForNode is a CodeBlockNode which means its value attribute accepts a wide range of values, see CodeBlockNode for more information. The else attributes accept a great ranges of inputs, since else is a reserved python keyword, you need to access it using the else_ attribute. Other attributes work as expected:

In [211]: red = RedBaron("for i in b: pass")

In [212]: red
Out[212]: 
0   for i in b: pass
    

In [213]: red[0].iterator = "i, j, k"

In [214]: red
Out[214]: 
0   for i, j, k in b: pass
    

In [215]: red[0].target = "[x for x in stuff if condition]"

In [216]: red
Out[216]: 
0   for i, j, k in [x for x in stuff if condition]: pass
    

In [217]: red[0].else_ = "do_stuff"

In [218]: red
Out[218]: 
0   for i, j, k in [x for x in stuff if condition]: pass
    else:
        do_stuff
    

In [219]: red[0].else_ = "else: foobar"

In [220]: red
Out[220]: 
0   for i, j, k in [x for x in stuff if condition]: pass
    else: 
        foobar
    

In [221]: red[0].else_ = "    else:\n        badly_indented_and_trailing\n\n\n\n"

In [222]: red
Out[222]: 
0   for i, j, k in [x for x in stuff if condition]: pass
    else:
        badly_indented_and_trailing

New in 0.8.

Async is a boolean attribute that determine if a function is async:

In [223]: red =  RedBaron("for a in b: pass")

In [224]: red[0].async_
Out[224]: False

In [225]: red[0].async_ = True

In [226]: red
Out[226]: 
0   async for a in b: pass
    

In [227]: red[0].async_ = False

In [228]: red
Out[228]: 
0   for a in b: pass

Warning

As of python 3.7 async and await are now reserved keywords so don’t uses red.async, it works as expected but won’t make your code forward compatible.

FromImportNode

A node representing a “from import” statement.

In [229]: RedBaron("from a import b")[0].help(deep=True)
FromImportNode()
  # identifiers: from_import, from_import_, fromimport, fromimportnode
  # helpers: full_path_modules, full_path_names, modules, names
  value ->
    * NameNode()
        # identifiers: name, name_, namenode
        value='a'
  targets ->
    * NameAsNameNode()
        # identifiers: name_as_name, name_as_name_, nameasname, nameasnamenode
        value='b'
        target=''

SetAttr

In [230]: red = RedBaron("from a import b")

In [231]: red
Out[231]: 0   from a import b

In [232]: red[0].value = "some.module"

In [233]: red
Out[233]: 0   from some.module import b

In [234]: red[0].targets = "a as b, c as d, e"

In [235]: red
Out[235]: 0   from some.module import a as b, c as d, e

Helpers

To reduce the complexity, 2 helpers method are provided:

In [236]: red = RedBaron("from foo.bar import baz as stuff, plop")

In [237]: red[0].names()  # names added to the context
Out[237]: ['stuff', 'plop']

In [238]: red[0].modules()  # modules imported
Out[238]: ['baz', 'plop']

In [239]: red[0].full_path_names()  # names added to the context with full path
Out[239]: ['foo.bar.stuff', 'foo.bar.plop']

In [240]: red[0].full_path_modules()  # modules imported with full path
Out[240]: ['foo.bar.baz', 'foo.bar.plop']

GeneratorComprehensionNode

A node representing a generator comprehension node.

In [241]: RedBaron("(x for y in z)")[0].help(deep=True)
GeneratorComprehensionNode()
  # identifiers: generator_comprehension, generator_comprehension_, generatorcomprehension, generatorcomprehensionnode
  result ->
    NameNode()
      # identifiers: name, name_, namenode
      value='x'
  generators ->
    * ComprehensionLoopNode()
        # identifiers: comprehension_loop, comprehension_loop_, comprehensionloop, comprehensionloopnode
        iterator ->
          NameNode()
            # identifiers: name, name_, namenode
            value='y'
        target ->
          NameNode()
            # identifiers: name, name_, namenode
            value='z'
        ifs ->

SetAttr

In [242]: red = RedBaron("(x for y in z)")

In [243]: red
Out[243]: 0   (x for y in z)

In [244]: red[0].result = "pouet"

In [245]: red
Out[245]: 0   (pouet for y in z)

In [246]: red[0].generators = "for artichaut in courgette"

In [247]: red
Out[247]: 0   (pouet for artichaut in courgette)

GetitemNode

A node representing a ‘get item’ access on a python object, in other words the ‘[stuff]’ in ‘some_object[stuff]’.

In [248]: RedBaron("a[b]")[0].value[1].help(deep=True)
GetitemNode()
  # identifiers: getitem, getitem_, getitemnode
  value ->
    NameNode()
      # identifiers: name, name_, namenode
      value='b'

SetAttr

In [249]: red = RedBaron("a[b]")

In [250]: red
Out[250]: 0   a[b]

In [251]: red[0].value[1].value = "1 + 1"

In [252]: red
Out[252]: 0   a[1 + 1]

GlobalNode

A node representing a global statement.

In [253]: RedBaron("global a")[0].help(deep=True)
GlobalNode()
  # identifiers: global, global_, globalnode
  value ->
    * NameNode()
        # identifiers: name, name_, namenode
        value='a'

SetAttr

In [254]: red = RedBaron("global a")

In [255]: red
Out[255]: 0   global a

In [256]: red[0].value = "stuff, plop"

In [257]: red
Out[257]: 0   global stuff, plop

IfNode

A node representing an if statement.

The IfNode, like the ElifNode or the ElseNode, is stored in an IfelseblockNode.

In [258]: RedBaron("if a: pass")[0].value[0].help(deep=True)
IfNode()
  # identifiers: if, if_, ifnode
  test ->
    NameNode()
      # identifiers: name, name_, namenode
      value='a'
  value ->
    * PassNode()
        # identifiers: pass, pass_, passnode

SetAttr

IfNode is a CodeBlockNode which means its value attribute accepts a wide range of values, see CodeBlockNode for more information. Other attributes work as expected:

In [259]: red = RedBaron("if a: pass")

In [260]: red
Out[260]: 
0   if a: pass
    

In [261]: red[0].value[0].test = "1 + 1 == 11"

In [262]: red
Out[262]: 
0   if 1 + 1 == 11: pass

IfelseblockNode

A node representing the conditional block composed of at least one if statement, zero or more elif statements and, at the end, an optional else statement. All those statements are stored in a list.

In [263]: RedBaron("if a: pass\nelif b: pass\nelse: pass\n")[0].help(deep=True)
IfelseblockNode()
  # identifiers: ifelseblock, ifelseblock_, ifelseblocknode
  value ->
    * IfNode()
        # identifiers: if, if_, ifnode
        test ->
          NameNode()
            # identifiers: name, name_, namenode
            value='a'
        value ->
          * PassNode()
              # identifiers: pass, pass_, passnode
    * ElifNode()
        # identifiers: elif, elif_, elifnode
        test ->
          NameNode()
            # identifiers: name, name_, namenode
            value='b'
        value ->
          * PassNode()
              # identifiers: pass, pass_, passnode
    * ElseNode()
        # identifiers: else, else_, elsenode
        value ->
          * PassNode()
              # identifiers: pass, pass_, passnode

SetAttr

Works as expected and is very flexible on its input:

  • the input is automatically put at the correct indentation
  • the input is automatically right strip
  • if the statement is followed, the correct number of blanks lines are added: 2 when at the root of the file, 1 when indented
In [264]: red = RedBaron("if a: pass\n")

In [265]: red
Out[265]: 
0   if a: pass
    

In [266]: red[0].value = "if a:\n    pass\nelif b:\n    pass\n\n\n"

In [267]: red
Out[267]: 
0   if a:
        pass
    elif b:
        pass
    

In [268]: red[0].value = "    if a:\n        pass"

In [269]: red
Out[269]: 
0   if a:
        pass
In [270]: red = RedBaron("if a:\n    pass\n\n\nplop")

In [271]: red
Out[271]: 
0   if a:
        pass
    
    
    
1   plop

In [272]: red[0].value = "    if a:\n        pass"

In [273]: red
Out[273]: 
0   if a:
        pass
    
    
    
1   plop
In [274]: red = RedBaron("while True:\n    if plop:\n        break\n\n    stuff")

In [275]: red
Out[275]: 
0   while True:
        if plop:
            break
    
        stuff
    

In [276]: red[0].value[1].value = "if a:\n    pass\nelif b:\n    pass\n\n\n"

In [277]: red
Out[277]: 
0   while True:
        if plop:
            break
    
        if a:
        pass
    elif b:
        pass

ImportNode

A node representing the import statement of the python language.

Be careful, this node and its subnodes are way more complex than what you can expect.

In [278]: RedBaron("import foo")[0].help(deep=True)
ImportNode()
  # identifiers: import, import_, importnode
  # helpers: modules, names
  value ->
    * DottedAsNameNode()
        # identifiers: dotted_as_name, dotted_as_name_, dottedasname, dottedasnamenode
        target=''
        value ->
          * NameNode()
              # identifiers: name, name_, namenode
              value='foo'

In [279]: RedBaron("import foo.bar.baz as stuff, another_thing.plop")[0].help(deep=True)
ImportNode()
  # identifiers: import, import_, importnode
  # helpers: modules, names
  value ->
    * DottedAsNameNode()
        # identifiers: dotted_as_name, dotted_as_name_, dottedasname, dottedasnamenode
        target='stuff'
        value ->
          * NameNode()
              # identifiers: name, name_, namenode
              value='foo'
          * NameNode()
              # identifiers: name, name_, namenode
              value='bar'
          * NameNode()
              # identifiers: name, name_, namenode
              value='baz'
    * DottedAsNameNode()
        # identifiers: dotted_as_name, dotted_as_name_, dottedasname, dottedasnamenode
        target=''
        value ->
          * NameNode()
              # identifiers: name, name_, namenode
              value='another_thing'
          * NameNode()
              # identifiers: name, name_, namenode
              value='plop'

SetAttr

Works as expected:

In [280]: red = RedBaron("import foo")

In [281]: red[0].value = "foo.bar.baz as plop, stuff, plop.dot"

In [282]: red
Out[282]: 0   import foo.bar.baz as plop, stuff, plop.dot

In [283]: red.help(deep=True)
0 -----------------------------------------------------
ImportNode()
  # identifiers: import, import_, importnode
  # helpers: modules, names
  value ->
    * DottedAsNameNode()
        # identifiers: dotted_as_name, dotted_as_name_, dottedasname, dottedasnamenode
        target='plop'
        value ->
          * NameNode()
              # identifiers: name, name_, namenode
              value='foo'
          * NameNode()
              # identifiers: name, name_, namenode
              value='bar'
          * NameNode()
              # identifiers: name, name_, namenode
              value='baz'
    * DottedAsNameNode()
        # identifiers: dotted_as_name, dotted_as_name_, dottedasname, dottedasnamenode
        target=''
        value ->
          * NameNode()
              # identifiers: name, name_, namenode
              value='stuff'
    * DottedAsNameNode()
        # identifiers: dotted_as_name, dotted_as_name_, dottedasname, dottedasnamenode
        target=''
        value ->
          * NameNode()
              # identifiers: name, name_, namenode
              value='plop'
          * NameNode()
              # identifiers: name, name_, namenode
              value='dot'

Helpers

To reduce the complexity, 2 helpers method are provided:

In [284]: red = RedBaron("import foo.bar.baz as stuff, another_thing.plop")

In [285]: red[0].modules()  # modules imported
Out[285]: ['foo.bar.baz', 'another_thing.plop']

In [286]: red[0].names()  # names added to the context
Out[286]: ['stuff', 'another_thing.plop']

IntNode

A python integer.

In [287]: RedBaron("42")[0].help()
IntNode()
  # identifiers: int, int_, intnode
  value='42'

KwargsOnlyMarkerNode

New in 0.7.

A node representing the “*” in arguments declaration to force keywords only arguments after itself.

In [288]: RedBaron("def a(*): pass")[0].arguments[0].help(deep=True)
KwargsOnlyMarkerNode()
  # identifiers: kwargs_only_marker, kwargs_only_marker_, kwargsonlymarker, kwargsonlymarkernode

LambdaNode

A node representing a lambda statement.

In [289]: RedBaron("lambda x: y")[0].help(deep=True)
LambdaNode()
  # identifiers: lambda, lambda_, lambdanode
  value ->
    NameNode()
      # identifiers: name, name_, namenode
      value='y'
  arguments ->
    * DefArgumentNode()
        # identifiers: def_argument, def_argument_, defargument, defargumentnode
        target ->
          NameNode()
            # identifiers: name, name_, namenode
            value='x'
        value ->
          None

SetAttr

Works as expected:

In [290]: red = RedBaron("lambda x: y")

In [291]: red
Out[291]: 0   lambda x: y

In [292]: red[0].arguments = "a, b=c, *d, **f"

In [293]: red
Out[293]: 0   lambda a, b=c, *d, **f: y

In [294]: red[0].value = "plop"

In [295]: red
Out[295]: 0   lambda a, b=c, *d, **f: plop

ListArgumentNode

A node representing a “star argument” in a function call or definition.

In [296]: RedBaron("def a(*b): pass")[0].arguments[0].help(deep=True)
ListArgumentNode()
  # identifiers: list_argument, list_argument_, listargument, listargumentnode
  value ->
    NameNode()
      # identifiers: name, name_, namenode
      value='b'

SetAttr

Works as expected:

In [297]: red = RedBaron("def a(*b): pass")

In [298]: red
Out[298]: 
0   def a(*b): pass
    

In [299]: red[0].arguments[0].value = "plop"

In [300]: red
Out[300]: 
0   def a(*plop): pass

ListComprehensionNode

A node representing a list comprehension node.

In [301]: RedBaron("[x for y in z]")[0].help(deep=True)
ListComprehensionNode()
  # identifiers: list_comprehension, list_comprehension_, listcomprehension, listcomprehensionnode
  result ->
    NameNode()
      # identifiers: name, name_, namenode
      value='x'
  generators ->
    * ComprehensionLoopNode()
        # identifiers: comprehension_loop, comprehension_loop_, comprehensionloop, comprehensionloopnode
        iterator ->
          NameNode()
            # identifiers: name, name_, namenode
            value='y'
        target ->
          NameNode()
            # identifiers: name, name_, namenode
            value='z'
        ifs ->

SetAttr

In [302]: red = RedBaron("[x for y in z]")

In [303]: red
Out[303]: 0   [x for y in z]

In [304]: red[0].result = "pouet"

In [305]: red
Out[305]: 0   [pouet for y in z]

In [306]: red[0].generators = "for artichaut in courgette"

In [307]: red
Out[307]: 0   [pouet for artichaut in courgette]

ListNode

A node representing python sugar syntactic notation for list.

In [308]: RedBaron("[1, 2, 3]")[0].help(deep=True)
ListNode()
  # identifiers: list, list_, listnode
  value ->
    * IntNode()
        # identifiers: int, int_, intnode
        value='1'
    * IntNode()
        # identifiers: int, int_, intnode
        value='2'
    * IntNode()
        # identifiers: int, int_, intnode
        value='3'

NameAsNameNode

A node representing an argument to the from import statement.

In [309]: RedBaron("from x import a as d")[0].targets[0].help(deep=True)
NameAsNameNode()
  # identifiers: name_as_name, name_as_name_, nameasname, nameasnamenode
  value='a'
  target='d'

SetAttr

In [310]: red = RedBaron("from x import a as d")

In [311]: red
Out[311]: 0   from x import a as d

In [312]: red[0].targets[0].value = "some_random_module"

In [313]: red
Out[313]: 0   from x import some_random_module as d

In [314]: red[0].targets[0].target = "stuff"

In [315]: red
Out[315]: 0   from x import some_random_module as stuff

NonlocalNode

New in 0.7.

A node representing a nonlocal statement.

In [316]: RedBaron("nonlocal a")[0].help(deep=True)
NonlocalNode()
  # identifiers: nonlocal, nonlocal_, nonlocalnode
  value ->
    * NameNode()
        # identifiers: name, name_, namenode
        value='a'

SetAttr

In [317]: red = RedBaron("nonlocal a")

In [318]: red
Out[318]: 0   nonlocal a

In [319]: red[0].value = "stuff, plop"

In [320]: red
Out[320]: 0   nonlocal stuff, plop

PrintNode

A node representing a print statement.

In [321]: RedBaron("print(stuff)")[0].help(deep=True)
PrintNode()
  # identifiers: print, print_, printnode
  destination ->
    None
  value ->
    * AssociativeParenthesisNode()
        # identifiers: associative_parenthesis, associative_parenthesis_, associativeparenthesis, associativeparenthesisnode
        value ->
          NameNode()
            # identifiers: name, name_, namenode
            value='stuff'

SetAttr

In [322]: red = RedBaron("print(stuff)")

In [323]: red
Out[323]: 0   print(stuff)

In [324]: red[0].destination = "some_file"

In [325]: red
Out[325]: 0   print >>some_file, (stuff)

In [326]: red[0].value = "a, b, c"

In [327]: red
Out[327]: 0   print >>some_file, a, b, c

In [328]: red[0].destination = ""

In [329]: red
Out[329]: 0   print a, b, c

In [330]: red[0].value = ""

In [331]: red
Out[331]: 0   print

RaiseNode

A node representing a raise statement.

In [332]: RedBaron("raise Exception(), foo, bar")[0].help(deep=True)
RaiseNode()
  # identifiers: raise, raise_, raisenode
  value ->
    AtomtrailersNode()
      # identifiers: atomtrailers, atomtrailers_, atomtrailersnode
      value ->
        * NameNode()
            # identifiers: name, name_, namenode
            value='Exception'
        * CallNode()
            # identifiers: call, call_, callnode
            value ->
  instance ->
    NameNode()
      # identifiers: name, name_, namenode
      value='foo'
  traceback ->
    NameNode()
      # identifiers: name, name_, namenode
      value='bar'

SetAttr

In [333]: red = RedBaron("raise stuff")

In [334]: red
Out[334]: 0   raise stuff

In [335]: red[0].value = "foo"

In [336]: red
Out[336]: 0   raise foo

In [337]: red[0].instance = "bar"

In [338]: red
Out[338]: 0   raise foo, bar

In [339]: red[0].traceback = "baz"

In [340]: red
Out[340]: 0   raise foo, bar, baz

ReprNode

A node representing python sugar syntactic notation for repr.

In [341]: RedBaron("`pouet`")[0].help(deep=True)
ReprNode()
  # identifiers: repr, repr_, reprnode
  value ->
    * NameNode()
        # identifiers: name, name_, namenode
        value='pouet'

ReturnNode

A node representing a return statement.

In [342]: RedBaron("return stuff")[0].help(deep=True)
ReturnNode()
  # identifiers: return, return_, returnnode
  value ->
    NameNode()
      # identifiers: name, name_, namenode
      value='stuff'

SetAttr

In [343]: red = RedBaron("return stuff")

In [344]: red
Out[344]: 0   return stuff

In [345]: red[0].value = "1 + 1"

In [346]: red
Out[346]: 0   return 1 + 1

In [347]: red[0].value = ""

In [348]: red
Out[348]: 0   return

SetNode

A node representing python sugar syntactic notation for set.

In [349]: RedBaron("{1, 2, 3}")[0].help(deep=True)
SetNode()
  # identifiers: set, set_, setnode
  value ->
    * IntNode()
        # identifiers: int, int_, intnode
        value='1'
    * IntNode()
        # identifiers: int, int_, intnode
        value='2'
    * IntNode()
        # identifiers: int, int_, intnode
        value='3'

SetComprehensionNode

A node representing a set comprehension node.

In [350]: RedBaron("{x for y in z}")[0].help(deep=True)
SetComprehensionNode()
  # identifiers: set_comprehension, set_comprehension_, setcomprehension, setcomprehensionnode
  result ->
    NameNode()
      # identifiers: name, name_, namenode
      value='x'
  generators ->
    * ComprehensionLoopNode()
        # identifiers: comprehension_loop, comprehension_loop_, comprehensionloop, comprehensionloopnode
        iterator ->
          NameNode()
            # identifiers: name, name_, namenode
            value='y'
        target ->
          NameNode()
            # identifiers: name, name_, namenode
            value='z'
        ifs ->

SetAttr

In [351]: red = RedBaron("{x for y in z}")

In [352]: red
Out[352]: 0   {x for y in z}

In [353]: red[0].result = "pouet"

In [354]: red
Out[354]: 0   {pouet for y in z}

In [355]: red[0].generators = "for artichaut in courgette"

In [356]: red
Out[356]: 0   {pouet for artichaut in courgette}

SliceNode

A node representing a slice, the “1:2:3” that can be found in a GetitemNode.

In [357]: RedBaron("a[1:-1:2]")[0].value[1].value.help(deep=True)
SliceNode()
  # identifiers: slice, slice_, slicenode
  has_two_colons=True
  lower ->
    IntNode()
      # identifiers: int, int_, intnode
      value='1'
  upper ->
    UnitaryOperatorNode()
      # identifiers: unitary_operator, unitary_operator_, unitaryoperator, unitaryoperatornode
      value='-'
      target ->
        IntNode()
          # identifiers: int, int_, intnode
          value='1'
  step ->
    IntNode()
      # identifiers: int, int_, intnode
      value='2'

SetAttr

In [358]: red = RedBaron("a[1:-1:2]")

In [359]: red
Out[359]: 0   a[1:-1:2]

In [360]: red[0].value[1].value.lower = "a"

In [361]: red
Out[361]: 0   a[a:-1:2]

In [362]: red[0].value[1].value.upper = "b"

In [363]: red
Out[363]: 0   a[a:b:2]

In [364]: red[0].value[1].value.step = "stuff"

In [365]: red
Out[365]: 0   a[a:b:stuff]

In [366]: red[0].value[1].value.step = ""

In [367]: red
Out[367]: 0   a[a:b]

SpaceNode

A formatting node representing a space. You’ll probably never have to deal with it except if you play with the way the file is rendered.

Those nodes will be hidden in formatting keys 99% of the time (the only exception is if it’s the last node of the file).

In [368]: RedBaron("1 + 1")[0].first_formatting[0].help()
SpaceNode()
  # identifiers: space, space_, spacenode
  value=' '

In [369]: RedBaron("1 + 1").help()
0 -----------------------------------------------------
BinaryOperatorNode()
  # identifiers: binary_operator, binary_operator_, binaryoperator, binaryoperatornode
  value='+'
  first ->
    IntNode()
      # identifiers: int, int_, intnode
      value='1'
  second ->
    IntNode()
      # identifiers: int, int_, intnode
      value='1'

StringChainNode

This is a special node that handle a particular way of writing a single string in python by putting several strings one after the other while only separated by spaces or endls.

In [370]: RedBaron("'a' r'b' b'c'")[0].help(deep=True)
StringChainNode()
  # identifiers: string_chain, string_chain_, stringchain, stringchainnode
  value ->
    * StringNode()
        # identifiers: string, string_, stringnode
        value="'a'"
    * RawStringNode()
        # identifiers: raw_string, raw_string_, rawstring, rawstringnode
        value="r'b'"
    * BinaryStringNode()
        # identifiers: binary_string, binary_string_, binarystring, binarystringnode
        value="b'c'"

SetAttr

In [371]: red = RedBaron("'a' r'b' b'c'")

In [372]: red
Out[372]: 0   'a' r'b' b'c'

In [373]: red[0].value = "'plip' 'plop'"

In [374]: red
Out[374]: 0   'plip' 'plop'

TernaryOperatorNode

A node representing the ternary operator expression.

In [375]: RedBaron("a if b else c")[0].help(deep=True)
TernaryOperatorNode()
  # identifiers: ternary_operator, ternary_operator_, ternaryoperator, ternaryoperatornode
  first ->
    NameNode()
      # identifiers: name, name_, namenode
      value='a'
  value ->
    NameNode()
      # identifiers: name, name_, namenode
      value='b'
  second ->
    NameNode()
      # identifiers: name, name_, namenode
      value='c'

SetAttr

In [376]: red = RedBaron("a if b else c")

In [377]: red
Out[377]: 0   a if b else c

In [378]: red[0].value = "some_test"

In [379]: red
Out[379]: 0   a if some_test else c

In [380]: red[0].first = "a_value"

In [381]: red
Out[381]: 0   a_value if some_test else c

In [382]: red[0].second = "another_value"

In [383]: red
Out[383]: 0   a_value if some_test else another_value

TryNode

A node representing a try statement. This node is responsible for holding the ExceptNode, FinallyNode and ElseNode.

In [384]: RedBaron("try: pass\nexcept FooBar: pass\nexcept Exception: pass\nelse: pass\nfinally: pass\n")[0].help(deep=True)
TryNode()
  # identifiers: try, try_, trynode
  else ->
    ElseNode()
      # identifiers: else, else_, elsenode
      value ->
        * PassNode()
            # identifiers: pass, pass_, passnode
  finally ->
    FinallyNode()
      # identifiers: finally, finally_, finallynode
      value ->
        * PassNode()
            # identifiers: pass, pass_, passnode
  value ->
    * PassNode()
        # identifiers: pass, pass_, passnode
  excepts ->
    * ExceptNode()
        # identifiers: except, except_, exceptnode
        delimiter=''
        exception ->
          NameNode()
            # identifiers: name, name_, namenode
            value='FooBar'
        target ->
          None
        value ->
          * PassNode()
              # identifiers: pass, pass_, passnode
    * ExceptNode()
        # identifiers: except, except_, exceptnode
        delimiter=''
        exception ->
          NameNode()
            # identifiers: name, name_, namenode
            value='Exception'
        target ->
          None
        value ->
          * PassNode()
              # identifiers: pass, pass_, passnode

SetAttr

TryNode is a CodeBlockNode which means its value attribute accepts a wide range of values, see CodeBlockNode for more information. For the else and the finally and the excepts attributes, TryNode is very flexible on the range of inputs it can get, like for a CodeBlockNode value’s attribute.

Important: Since else and finally are reserved keywords in python, you need to append a _ to those attributes name to access/modify them: node.else_ and node.finally_.

In [385]: red = RedBaron("try:\n    pass\nexcept:\n    pass\n")

In [386]: red
Out[386]: 
0   try:
        pass
    except:
        pass
    

In [387]: red[0].else_ = "do_stuff"

In [388]: red
Out[388]: 
0   try:
        pass
    except:
        pass
    else:
        do_stuff
    

In [389]: red[0].else_ = "else: foobar"

In [390]: red
Out[390]: 
0   try:
        pass
    except:
        pass
    else: 
        foobar
    

In [391]: red[0].else_ = "    else:\n        badly_indented_and_trailing\n\n\n\n"

In [392]: red
Out[392]: 
0   try:
        pass
    except:
        pass
    else:
        badly_indented_and_trailing
    

# input management of finally_ works the same way than for else_
In [393]: red[0].finally_ = "close_some_stuff"

In [394]: red
Out[394]: 
0   try:
        pass
    except:
        pass
    else:
        badly_indented_and_trailing
    finally:
        close_some_stuff
    

In [395]: red[0].else_ = ""

In [396]: red
Out[396]: 
0   try:
        pass
    except:
        pass
    finally:
        close_some_stuff
    

In [397]: red[0].finally_ = ""

In [398]: red
Out[398]: 
0   try:
        pass
    except:
        pass
    

In [399]: red[0].excepts = "except A as b:\n    pass"

In [400]: red
Out[400]: 
0   try:
        pass
    except A as b:
        pass
    

In [401]: red[0].excepts = "except X:\n    pass\nexcept Y:\n    pass"

In [402]: red
Out[402]: 
0   try:
        pass
    except X:
        pass
    except Y:
        pass
    

# You **CAN'T** do this red[0].excepts = "foobar"

TypedNameNode

A node representing a typed argument in a function definition.

In [403]: RedBaron("def a(b: c): ...")[0].arguments[0].help(deep=True)
DefArgumentNode()
  # identifiers: def_argument, def_argument_, defargument, defargumentnode
  target ->
    TypedNameNode()
      # identifiers: typed_name, typed_name_, typedname, typednamenode
      value='b'
      annotation ->
        NameNode()
          # identifiers: name, name_, namenode
          value='c'
  value ->
    None

In [404]: RedBaron("def a(b: c): ...")[0].arguments[0].target.help(deep=True)
TypedNameNode()
  # identifiers: typed_name, typed_name_, typedname, typednamenode
  value='b'
  annotation ->
    NameNode()
      # identifiers: name, name_, namenode
      value='c'

SetAttr

In [405]: red = RedBaron("def a(b: c): ...")[0].arguments[0].target

In [406]: red
Out[406]: b: c

In [407]: red[0].value = "stuff"

TypeErrorTraceback (most recent call last)
<ipython-input-407-54097f199dbd> in <module>()
----> 1 red[0].value = "stuff"

/home/docs/checkouts/readthedocs.org/user_builds/redbaron/envs/latest/local/lib/python2.7/site-packages/redbaron/base_nodes.pyc in __getitem__(self, key)
    724             return self.value[key]
    725 
--> 726         raise TypeError("'%s' object does not support indexing" % self.__class__)
    727 
    728     def __getslice__(self, i, j):

TypeError: '<class 'redbaron.nodes.TypedNameNode'>' object does not support indexing

In [408]: red
Out[408]: b: c

In [409]: red[0].annotation = "List[Int]"

TypeErrorTraceback (most recent call last)
<ipython-input-409-85383f38f039> in <module>()
----> 1 red[0].annotation = "List[Int]"

/home/docs/checkouts/readthedocs.org/user_builds/redbaron/envs/latest/local/lib/python2.7/site-packages/redbaron/base_nodes.pyc in __getitem__(self, key)
    724             return self.value[key]
    725 
--> 726         raise TypeError("'%s' object does not support indexing" % self.__class__)
    727 
    728     def __getslice__(self, i, j):

TypeError: '<class 'redbaron.nodes.TypedNameNode'>' object does not support indexing

In [410]: red
Out[410]: b: c

TupleNode

A node representing python sugar syntactic notation for tuple.

In [411]: RedBaron("(1, 2, 3)")[0].help(deep=True)
TupleNode()
  # identifiers: tuple, tuple_, tuplenode
  with_parenthesis=True
  value ->
    * IntNode()
        # identifiers: int, int_, intnode
        value='1'
    * IntNode()
        # identifiers: int, int_, intnode
        value='2'
    * IntNode()
        # identifiers: int, int_, intnode
        value='3'

UnitaryOperatorNode

A node representing a number sign modification operator like -2 or +42.

In [412]: RedBaron("-1")[0].help(deep=True)
UnitaryOperatorNode()
  # identifiers: unitary_operator, unitary_operator_, unitaryoperator, unitaryoperatornode
  value='-'
  target ->
    IntNode()
      # identifiers: int, int_, intnode
      value='1'

SetAttr

In [413]: red = RedBaron("-1")

In [414]: red
Out[414]: 0   -1

In [415]: red[0].target = "42"

In [416]: red
Out[416]: 0   -42

In [417]: red[0].value = "+"

In [418]: red
Out[418]: 0   +42

YieldNode

A node representing a yield statement.

In [419]: RedBaron("yield 42")[0].help(deep=True)
YieldNode()
  # identifiers: yield, yield_, yieldnode
  value ->
    IntNode()
      # identifiers: int, int_, intnode
      value='42'

SetAttr

In [420]: red = RedBaron("yield 42")

In [421]: red
Out[421]: 0   yield 42

In [422]: red[0].value = "stuff"

In [423]: red
Out[423]: 0   yield stuff

In [424]: red[0].value = ""

In [425]: red
Out[425]: 0   yield

YieldAtomNode

A node representing a yield statement surrounded by parenthesis.

In [426]: RedBaron("(yield 42)")[0].help(deep=True)
YieldAtomNode()
  # identifiers: yield_atom, yield_atom_, yieldatom, yieldatomnode
  value ->
    IntNode()
      # identifiers: int, int_, intnode
      value='42'

SetAttr

In [427]: red = RedBaron("(yield 42)")

In [428]: red
Out[428]: 0   (yield 42)

In [429]: red[0].value = "stuff"

In [430]: red
Out[430]: 0   (yield stuff)

In [431]: red[0].value = ""

In [432]: red
Out[432]: 0   (yield)

YieldFromNode

New in 0.7.

A node representing a “yield from” statement.

In [433]: RedBaron("yield from 42")[0].help(deep=True)
YieldFromNode()
  # identifiers: yield_from, yield_from_, yieldfrom, yieldfromnode
  value ->
    IntNode()
      # identifiers: int, int_, intnode
      value='42'

SetAttr

In [434]: red = RedBaron("yield from 42")

In [435]: red
Out[435]: 0   yield from 42

In [436]: red[0].value = "stuff"

In [437]: red
Out[437]: 0   yield from stuff

WhileNode

A node representing a while loop.

In [438]: RedBaron("while condition:\n    pass")[0].help(deep=True)
WhileNode()
  # identifiers: while, while_, whilenode
  test ->
    NameNode()
      # identifiers: name, name_, namenode
      value='condition'
  else ->
    None
  value ->
    * PassNode()
        # identifiers: pass, pass_, passnode

SetAttr

WhileNode is a CodeBlockNode which means its value attribute accepts a wide range of values, see CodeBlockNode for more information. The else attributes accept a great ranges of inputs, since else is a reserved python keyword, you need to access it using the else_ attribute. Other attributes work as expected:

In [439]: red = RedBaron("while condition: pass")

In [440]: red
Out[440]: 
0   while condition: pass
    

In [441]: red[0].test = "a is not None"

In [442]: red
Out[442]: 
0   while a is not None: pass
    

In [443]: red[0].else_ = "do_stuff"

In [444]: red
Out[444]: 
0   while a is not None: pass
    else:
        do_stuff
    

In [445]: red[0].else_ = "else: foobar"

In [446]: red
Out[446]: 
0   while a is not None: pass
    else: 
        foobar
    

In [447]: red[0].else_ = "    else:\n        badly_indented_and_trailing\n\n\n\n"

In [448]: red
Out[448]: 
0   while a is not None: pass
    else:
        badly_indented_and_trailing

WithContext

A node representing a with statement.

In [449]: RedBaron("with a: pass")[0].help(deep=True)
WithNode()
  # identifiers: with, with_, withnode
  async=False
  contexts ->
    * WithContextItemNode()
        # identifiers: with_context_item, with_context_item_, withcontextitem, withcontextitemnode
        value ->
          NameNode()
            # identifiers: name, name_, namenode
            value='a'
        as ->
          None
  value ->
    * PassNode()
        # identifiers: pass, pass_, passnode

WithContextItemNode

A node representing one of the context manager items in a with statement.

In [450]: RedBaron("with a as b: pass")[0].contexts[0].help(deep=True)
WithContextItemNode()
  # identifiers: with_context_item, with_context_item_, withcontextitem, withcontextitemnode
  value ->
    NameNode()
      # identifiers: name, name_, namenode
      value='a'
  as ->
    NameNode()
      # identifiers: name, name_, namenode
      value='b'

SetAttr

In [451]: red = RedBaron("with a: pass")

In [452]: red
Out[452]: 
0   with a: pass
    

In [453]: red[0].contexts[0].value = "plop"

In [454]: red
Out[454]: 
0   with plop: pass
    

In [455]: red[0].contexts[0].as_ = "stuff"

In [456]: red
Out[456]: 
0   with plop as stuff: pass
    

In [457]: red[0].contexts[0].as_ = ""

In [458]: red
Out[458]: 
0   with plop: pass

WithNode

A node representing a with statement.

In [459]: RedBaron("with a as b, c: pass")[0].help(deep=True)
WithNode()
  # identifiers: with, with_, withnode
  async=False
  contexts ->
    * WithContextItemNode()
        # identifiers: with_context_item, with_context_item_, withcontextitem, withcontextitemnode
        value ->
          NameNode()
            # identifiers: name, name_, namenode
            value='a'
        as ->
          NameNode()
            # identifiers: name, name_, namenode
            value='b'
    * WithContextItemNode()
        # identifiers: with_context_item, with_context_item_, withcontextitem, withcontextitemnode
        value ->
          NameNode()
            # identifiers: name, name_, namenode
            value='c'
        as ->
          None
  value ->
    * PassNode()
        # identifiers: pass, pass_, passnode

SetAttr

WithNode is a CodeBlockNode which means its value attribute accepts a wide range of values, see CodeBlockNode for more information. Other attributes work as expected:

In [460]: red = RedBaron("with a: pass")

In [461]: red
Out[461]: 
0   with a: pass
    

In [462]: red[0].contexts = "b as plop, stuff()"

In [463]: red
Out[463]: 
0   with b as plop, stuff(): pass

New in 0.8.

Async is a boolean attribute that determine if a function is async:

In [464]: red =  RedBaron("with a as b: pass")

In [465]: red[0].async_
Out[465]: False

In [466]: red[0].async_ = True

In [467]: red
Out[467]: 
0   async with a as b: pass
    

In [468]: red[0].async_ = False

In [469]: red
Out[469]: 
0   with a as b: pass

Warning

As of python 3.7 async and await are now reserved keywords so don’t uses red.async, it works as expected but won’t make your code forward compatible.