Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse Python 2.x with Python 3.x ast module?

I recently wrote a Sublime Text 3 plugin that parses Python code and issues some stats from it.

Nothing too complex, except I noticed Sublime Text 3 uses Python 3.x and apparently the ast module expects to see Python 3.x code as well. I looked at the documentation for the ast module but couldn't find anything that allows me to specify the version.

Obviously this causes issues when parsing perfectly valid Python 2.7 code.

Is there a way to specify or somehow detect/guess the Python version ? Or to allow the parser to be more flexible ?

like image 621
ereOn Avatar asked Oct 30 '14 14:10

ereOn


People also ask

What is the AST module in Python?

The ast module helps Python applications to process trees of the Python abstract syntax grammar. The abstract syntax itself might change with each Python release; this module helps to find out programmatically what the current grammar looks like. An abstract syntax tree can be generated by passing ast.

What is AST Literal_eval in Python?

The ast. literal_eval method is one of the helper functions that helps traverse an abstract syntax tree. This function evaluates an expression node or a string consisting of a Python literal or container display.

Is AST part of Python standard library?

ast is a module in the python standard library. Python codes need to be converted to an Abstract Syntax Tree (AST) before becoming “byte code”(. pyc files). Generating AST is the most important function of ast, but there are more ways one can use the module.


1 Answers

No, the ast module can only handle Python code for the version of Python it is shipped with. That's because under the hood, the exact same parser is used to compile your Python code into byte code; all the ast module does is give you the intermediary AST tree. This parser has no 'backwards compatible' mode.

You'll need to implement your own parser if you want to parse different source code from Python versions. This certainly appears the path that Jedi (a Python autocompletion library) took.

Looking at the SublimeCodeIntel packaging of CodeIntel2, I see that that package bases its Python and Python 3 parsers on SilverCity, which has Python bindings. Perhaps that project would be a suitable starting point for your own.

like image 80
Martijn Pieters Avatar answered Nov 01 '22 15:11

Martijn Pieters