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'
  annotation ->
    None
  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'
  annotation ->
    None
  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 ->
    * 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

In [92]: RedBaron("class SomeAwesomeName(A, B, metaclass=C): pass")[0].help(deep=True)
ClassNode()
  # identifiers: class, class_, classnode
  # default test value: name
  name='SomeAwesomeName'
  parenthesis=True
  decorators ->
  inherit_from ->
    * NameNode()
        # identifiers: name, name_, namenode
        value='A'
    * NameNode()
        # identifiers: name, name_, namenode
        value='B'
    * CallArgumentNode()
        # identifiers: call_argument, call_argument_, callargument, callargumentnode
        target ->
          NameNode()
            # identifiers: name, name_, namenode
            value='metaclass'
        value ->
          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 [93]: red = RedBaron("class SomeAwesomeName(A, B, C): pass")

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

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

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

In [97]: red
Out[97]: 
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 [98]: 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 [99]: 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 [100]: red = RedBaron("42 > 30")

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

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

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

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

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

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

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

ComprehensionIfNode

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

In [108]: 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 [109]: red = RedBaron("[x for x in x if condition]")

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

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

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

ComprehensionLoopNode

The node represents the loop part of a comprehension structure.

In [113]: 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 [114]: red = RedBaron("[x for y in z]")

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

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

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

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

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

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

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

DecoratorNode

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

In [122]: 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'
            annotation ->
              None

SetAttr

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

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

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

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

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

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

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

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

DefNode

A node representing a function definition.

In [131]: 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'
  return_annotation ->
    None
  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 [132]: red = RedBaron("def stuff():\n    body\n")

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

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

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

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

Decorators might be a bit less intuitive:

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

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

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

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

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

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

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

New in 0.7.

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

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

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

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

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

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

In [149]: red
Out[149]: 
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.

New in 0.9

Return annotation management:

In [150]: red =  RedBaron("def stuff():\n    return 42\n")

In [151]: red
Out[151]: 
0   def stuff():
        return 42
    

In [152]: red[0].return_annotation = "Int"

In [153]: red
Out[153]: 
0   def stuff() -> Int:
        return 42
    

In [154]: red[0].return_annotation = ""

In [155]: red
Out[155]: 
0   def stuff():
        return 42

DefArgumentNode

A node representing an argument in a function definition.

In [156]: 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'
  annotation ->
    None
  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'
  annotation ->
    None
  value ->
    NameNode()
      # identifiers: name, name_, namenode
      value='d'

SetAttr

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

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

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

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

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

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

New in 0.9

Annotations:

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

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

In [165]: red[0].arguments[0].annotation = "Int"

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

In [167]: red[0].arguments[0].annotation
Out[167]: Int

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

DelNode

A node representing a del statement.

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

SetAttr

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

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

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

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

DictArgumentNode

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

In [174]: 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'
  annotation ->
    None

SetAttr

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

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

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

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

New in 0.9

Annotations:

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

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

In [181]: red[0].arguments[0].annotation = "Int"

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

In [183]: red[0].arguments[0].annotation
Out[183]: Int

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

DictNode

A node representing python sugar syntactic notation for dict.

In [185]: 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 [186]: 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 [187]: red = RedBaron("{a: b for c in d}")

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

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

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

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

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

DottedAsNameNode

A node representing an argument to the import node.

In [193]: 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 [194]: red = RedBaron("import a.b.c as d")

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

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

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

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

In [199]: red
Out[199]: 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 [200]: 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 [201]: 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 [202]: red = RedBaron("if a: pass\nelif b: pass")

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

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

In [205]: red
Out[205]: 
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 [206]: 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 [207]: 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 [208]: RedBaron("\n")[0].help()
EndlNode()
  # identifiers: endl, endl_, endlnode
  value='\n'
  indent=''

In [209]: 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 [210]: 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 [211]: red = RedBaron("try: pass\nexcept: pass")

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

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

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

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

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

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

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

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

ExecNode

A node representing an exec statement.

In [219]: 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 [220]: red = RedBaron("exec 'stuff'")

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

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

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

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

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

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

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

FinallyNode

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

In [228]: 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 [229]: 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 [230]: red = RedBaron("for i in b: pass")

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

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

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

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

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

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

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

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

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

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

In [241]: red
Out[241]: 
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 [242]: red =  RedBaron("for a in b: pass")

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

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

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

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

In [247]: red
Out[247]: 
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 [248]: 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 [249]: red = RedBaron("from a import b")

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

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

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

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

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

Helpers

To reduce the complexity, 2 helpers method are provided:

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

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

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

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

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

GeneratorComprehensionNode

A node representing a generator comprehension node.

In [260]: 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 [261]: red = RedBaron("(x for y in z)")

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

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

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

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

In [266]: red
Out[266]: 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 [267]: RedBaron("a[b]")[0].value[1].help(deep=True)
GetitemNode()
  # identifiers: getitem, getitem_, getitemnode
  value ->
    NameNode()
      # identifiers: name, name_, namenode
      value='b'

SetAttr

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

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

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

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

GlobalNode

A node representing a global statement.

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

SetAttr

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

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

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

In [276]: red
Out[276]: 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 [277]: 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 [278]: red = RedBaron("if a: pass")

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

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

In [281]: red
Out[281]: 
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 [282]: 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 [283]: red = RedBaron("if a: pass\n")

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

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

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

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

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

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

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

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

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

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

In [296]: red
Out[296]: 
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 [297]: 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 [298]: 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 [299]: red = RedBaron("import foo")

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

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

In [302]: 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 [303]: red = RedBaron("import foo.bar.baz as stuff, another_thing.plop")

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

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

IntNode

A python integer.

In [306]: 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 [307]: 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 [308]: 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'
        annotation ->
          None
        value ->
          None

SetAttr

Works as expected:

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

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

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

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

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

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

ListArgumentNode

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

In [315]: 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'
  annotation ->
    None

SetAttr

Works as expected:

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

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

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

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

New in 0.9

Annotations:

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

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

In [322]: red[0].arguments[0].annotation = "Int"

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

In [324]: red[0].arguments[0].annotation
Out[324]: Int

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

ListComprehensionNode

A node representing a list comprehension node.

In [326]: 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 [327]: red = RedBaron("[x for y in z]")

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

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

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

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

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

ListNode

A node representing python sugar syntactic notation for list.

In [333]: 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 [334]: 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 [335]: red = RedBaron("from x import a as d")

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

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

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

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

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

NonlocalNode

New in 0.7.

A node representing a nonlocal statement.

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

SetAttr

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

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

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

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

PrintNode

A node representing a print statement.

In [346]: 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 [347]: red = RedBaron("print(stuff)")

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

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

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

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

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

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

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

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

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

RaiseNode

A node representing a raise statement.

In [357]: RedBaron("raise Exception(), foo, bar")[0].help(deep=True)
RaiseNode()
  # identifiers: raise, raise_, raisenode
  comma_or_from=','
  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 [358]: red = RedBaron("raise stuff")

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

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

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

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

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

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

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

New in 0.9

How to deal with the “raise from” notation: (by default a comma is inserted to avoid breaking backward compatibility)

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

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

In [368]: red[0].instance = "foo"

In [369]: red
Out[369]: 0   raise stuff, foo

In [370]: red[0].comma_or_from = "from"

In [371]: red
Out[371]: 0   raise stuff from foo

In [372]: red[0].comma_or_from = ","

In [373]: red
Out[373]: 0   raise stuff, foo

In [374]: red[0].instance = ""

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

ReprNode

A node representing python sugar syntactic notation for repr.

In [376]: 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 [377]: RedBaron("return stuff")[0].help(deep=True)
ReturnNode()
  # identifiers: return, return_, returnnode
  value ->
    NameNode()
      # identifiers: name, name_, namenode
      value='stuff'

SetAttr

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

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

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

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

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

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

SetNode

A node representing python sugar syntactic notation for set.

In [384]: 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 [385]: 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 [386]: red = RedBaron("{x for y in z}")

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

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

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

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

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

SliceNode

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

In [392]: 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 [393]: red = RedBaron("a[1:-1:2]")

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

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

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

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

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

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

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

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

In [402]: red
Out[402]: 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 [403]: RedBaron("1 + 1")[0].first_formatting[0].help()
SpaceNode()
  # identifiers: space, space_, spacenode
  value=' '

In [404]: 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'

StarExpressionNode

New in 0.9

A node representing the result of a deconstruction in an assignment.

In [405]: red = RedBaron("a, *b = c")

In [406]: red
Out[406]: 0   a, *b = c

In [407]: red[0].target[1].help()
StarExpressionNode()
  # identifiers: star_expression, star_expression_, starexpression, starexpressionnode
  value ->
    NameNode()
      # identifiers: name, name_, namenode
      value='b'

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 [408]: 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 [409]: red = RedBaron("'a' r'b' b'c'")

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

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

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

TernaryOperatorNode

A node representing the ternary operator expression.

In [413]: 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 [414]: red = RedBaron("a if b else c")

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

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

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

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

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

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

In [421]: red
Out[421]: 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 [422]: 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 [423]: red = RedBaron("try:\n    pass\nexcept:\n    pass\n")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

TupleNode

A node representing python sugar syntactic notation for tuple.

In [441]: 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 [442]: 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 [443]: red = RedBaron("-1")

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

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

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

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

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

YieldNode

A node representing a yield statement.

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

SetAttr

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

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

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

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

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

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

YieldAtomNode

A node representing a yield statement surrounded by parenthesis.

In [456]: 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 [457]: red = RedBaron("(yield 42)")

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

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

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

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

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

YieldFromNode

New in 0.7.

A node representing a “yield from” statement.

In [463]: 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 [464]: red = RedBaron("yield from 42")

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

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

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

WhileNode

A node representing a while loop.

In [468]: 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 [469]: red = RedBaron("while condition: pass")

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

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

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

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

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

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

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

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

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

WithContext

A node representing a with statement.

In [479]: 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 [480]: 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 [481]: red = RedBaron("with a: pass")

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

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

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

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

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

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

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

WithNode

A node representing a with statement.

In [489]: 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 [490]: red = RedBaron("with a: pass")

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

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

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

New in 0.8.

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

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

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

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

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

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

In [499]: red
Out[499]: 
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.