How to find list comprehension in python code

2024/10/6 22:11:28

I want to find a list comprehension in python source code, for that I tried to use Pygments, but it didn't find the way to do that.

To be more specific, I want to do a function that recognize all the posible list comprehension. 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)]

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

It is also valid a solution with regular expression.

Thank you

Answer

You can use the ast library to parse Python code into a syntax tree and then walk the parsed tree to look for ListComp expressions.

Here's a simple example which prints the line numbers at which list comprehensions were found in the Python code passed via stdin:

import ast
import sysprog = 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
https://en.xdnf.cn/q/73183.html

Related Q&A

Save XLSX file to a specified location using OpenPyXL

Im having an issue saving my file to a certain location on my Raspberry PI (Raspbian) computer. Im wanting the XLSX file to be saved directly to my desktop rather than the folder holding the Python Sc…

Pandas read csv dateint columns to datetime

Im new to both StackOverflow and pandas. I am trying to read in a large CSV file with stock market bin data in the following format:date,time,open,high,low,close,volume,splits,earnings,dividends,sym 20…

Pydantic - Dynamically create a model with multiple base classes?

From the pydantic docs I understand this: import pydanticclass User(pydantic.BaseModel):id: intname: strclass Student(pydantic.BaseModel):semester: int# this works as expected class Student_User(User, …

Handling nested elements with Python lxml

Given the simple XML data below:<book><title>My First Book</title><abstract><para>First paragraph of the abstract</para><para>Second paragraph of the abstract&…

Easiest way to plot data on country map with python

Could not delete question. Please refer to question: Shade states of a country according to dictionary values with Basemap I want to plot data (number of sick people for a certain year) on each state o…

How to resize QMainWindow after removing all DockWidgets?

I’m trying to make an application consisting of a QMainWindow, the central widget of which is a QToolBar (it may not be usual, but for my purpose the toolbar’s well suited). Docks are allowed below o…

Python: sorting a list by column [duplicate]

This question already has answers here:How to sort a list/tuple of lists/tuples by the element at a given index(11 answers)Closed 8 years ago.How can I sort a list-of-lists by "column", i.e. …

How to make setuptools clone git dependencies recursively?

I want to let setuptools install Phoenix in my project and thus addedsetup(...dependency_links = ["git+https://github.com/wxWidgets/Phoenix.git#egg=Phoenix"],install_requires = ["Phoenix…

Stable sorting in Jinja2

It is possible to apply the sort filter in Jinja2 successively to sort a list first by one attribute, then by another? This seems like a natural thing to do, but in my testing, the preceeding sort is …

Factor to complex roots using sympy

I cant figure out how to factor an polynomial expression to its complex roots.>>> from sympy import * >>> s = symbol(s) >>> factor(s**2+1)2 s + 1