Hi,
I’m looking for an easy way to parse python code.
class A:
def get():
for i in "bl":
print(i)
class B:
def get():
for i in "bl":
print(i)
what I want at the end is to identify each for loop or get metthod.
the only difference between the 2 for loop and 2 get method sis that they own a different class. How could I know it ?
You can access Python’s own parser output with the ast module; ast.parse() returns a tree of node objects representing different grammar components, and then you could use a NodeVisitor subclass to help track the relationships between elements.
lib2to3 is built on top of the AST (with comments retained). If you must have that level of detail retained you would be better off using typed-ast though. Not that you need that to determine what class a method belongs to.
That’s quite a limitation. Why is that? Python 3.3 is no longer supported even, the last regular release was over 5 years ago, and the last security fix release dates from September 2017. You’d be better off with a locally compiled Python release.
We really should get them to upgrade their embedded Python version.
Other than that you can always use a child process from your plugin. The black code formatter requires Python 3.6 and is run as a long-running server by the sublime plugin.
I misunderstood how much typed-ast preserves; it records the type-specific information from the PEP-documented comment syntax, so doesn’t preserve all comment content. Sorry about that.
That was my understanding, too. The trees that lib2to3 uses are much closer to the concrete parse trees produced by Python’s parser module than to Python’s AST.