python/ast: evaluate an ast.Subscript node
Question: I'm using ast to parse python files and I can't work out how to get an
ast.Subscript node to evaluate. I can't even see how to get the text out of it
(so I could use eval(text) ). Can anyone see what I'm missing?

For example, here the default value for the A arg is an expression which I
want to evaluate. Ast returns the default value as an ast.Subscript node. How
can I evaluate that?

    
    
    import ast
    import os
    
    text = """
    def test(A=os.environ["USER"][0]):
        return A
    """
    
    fnDef = ast.parse(text).body[0]
    argDefault = fnDef.args.defaults[0]
    


Answer: Using `ast.dump(node)`, you can see what your node is composed of. In your
case (indentation is mine):

    
    
    print(ast.dump(fnDef))
    > FunctionDef(name='test', 
            args=arguments(
                args=[arg(arg='A', annotation=None)], 
                vararg=None, 
                varargannotation=None, 
                kwonlyargs=[], 
                kwarg=None, 
                kwargannotation=None, 
                defaults=[
                    Subscript(
                        value=Subscript(
                            value=Attribute(
                                value=Name(id='os', ctx=Load()),
                                attr='environ', ctx=Load()),
                            slice=Index(value=Str(s='USER')), 
                            ctx=Load()), 
                        slice=Index(value=Num(n=0)), 
                        ctx=Load())], 
                kw_defaults=[]), 
            body=[Return(value=Name(id='A', ctx=Load()))], 
            decorator_list=[], 
            returns=None)
    

As you can see, your Subscript nodes are composed of a value, a slice and a
ctx. The first slice (`["USER"]`) is an Index which value is a Str node, the
second (`[0]`) slice is an Index which value is a Num node.

You can also see that in the [abstract
grammar](https://docs.python.org/3.4/library/ast.html#abstract-grammar
"Python's grammar") (see the 'slice' type).

