How to find a list comprehension in python code

I want to find an understanding of the list in the python source code since I tried to use Pygments but couldn't find a way to do this.

To be more specific, I want to make a function that recognizes all understandable list comprehensions. For example:

[x**2 for x in range(5)]

[x for x in vec if x >= 0]

[num for elem in vec for num in elem]

[str(round(pi, i)) for i in range(1, 6)]

These examples are from https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions

This is also a fair regex solution.

thanks

+4
source share
2 answers

ast Python , , ListComp .

, , Python, stdin:

import ast
import sys

prog = ast.parse(sys.stdin.read())
listComps = (node for node in ast.walk(prog) if type(node) is ast.ListComp)
for comp in listComps:
    print "List comprehension at line %d" % comp.lineno
+4

ast .

import ast

my_code = """
print "Hello"
y = [x ** 2 for x in xrange(30)]
"""

module = ast.parse(my_code)
for node in ast.walk(module):
    if type(node) == ast.ListComp:
        print node.lineno  # 3
        print node.col_offset  # 5
        print node.elt  # <_ast.BinOp object at 0x0000000002326EF0>
+3

Source: https://habr.com/ru/post/1626989/


All Articles