Search code examples
pythonpython-3.xabstract-syntax-treepython-internals

Understanding ctx in Python's ast


What is the ctx argument in the Python AST representation? For example:

>>> print(ast.dump(ast.parse('-a')))
Module(body=[Expr(value=UnaryOp(op=USub(), operand=Name(id='a', ctx=Load())))])

In other words, what does ctx=Load() mean or do? The only information I'm able to see from the docs is that the ctx may be one of:

expr_context = Load | Store | Del | AugLoad | AugStore | Param

https://docs.python.org/3.7/library/ast.html. Could someone explain the various expr_context and what those do? I suppose lhs and rhs are the store/load:

>>> print(ast.dump(ast.parse('b=-a')))
Module(body=[Assign(targets=[Name(id='b', ctx=Store())], value=UnaryOp(op=USub(), operand=Name(id='a', ctx=Load())))])

But beyond that, what are all the other options?


Update: Also, yes there is another question similar to this, Python AST: several semantics unclear, e.g. expr_context, but the accepted answer starts with "After some more testing and guessing:..." and it pretty light (to say the least) on details. I'm hoping that someone who actually understands the ast module a bit more can provide a more thorough answer.


Solution

  • An expression in Load context is having its value computed. Store means an expression is being assigned to (including in ways like being used as a with or for target), and Del means that an expression is being deleted (with del). This is described in the Python 3.9 ast docs, which are much better than the 3.7 docs.

    Param, AugLoad, and AugStore can be safely ignored. As of Python 3.7, they never appear in an actual AST, and as of 3.9, they are completely gone, even at the implementation level. In 3.7, AugLoad and AugStore sometimes appeared in temporary objects created internally by the compiler, but never in an actual AST. As far as I can tell, Param hasn't been used ever since the introduction of function annotations forced a redesign of the AST representation for function parameters in Python 3.0.