Исследование структуры кода с помощью модуля ast
При работе с кодом на Python, иногда возникает необходимость анализа его структуры. Для этого идеально подходит модуль ast (Abstract Syntax Trees), который предоставляет мощные инструменты для работы с абстрактными синтаксическими деревьями.
Что такое ast?
ast - это модуль Python, который позволяет разбирать и анализировать исходный код на Python, представляя его в виде абстрактного синтаксического дерева (AST). AST представляет собой структурированное представление кода, которое легко интерпретировать и анализировать.
Пример использования модуля ast:
import ast
code = "print('Hello, ast!')"
tree = ast.parse(code)
print(ast.dump(tree))
В данном примере мы использовали функцию ast.parse для разбора строки кода с помощью модуля ast. Функция ast.dump выводит структуру AST в удобочитаемом формате.
Анализ структуры кода:
import ast
code = """
def greet(name):
print(f'Hello, {name}!')
"""
tree = ast.parse(code)
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
print(f"Найдена функция: {node.name}")
elif isinstance(node, ast.Print):
print("Обнаружен оператор печати")
В данном примере мы использовали модуль ast для анализа структуры кода. Функция ast.walk позволяет обойти все узлы AST, а затем мы проверяем их типы для выделения определенных элементов, таких как функции или операторы.
Модуль ast также предоставляет возможности для более сложных операций, таких как изменение кода, создание новых выражений и многое другое.
#python#ast#анализкода
#python
FieldStation42 is a project that lets you experience old TV like it was in the past. It uses a Raspberry Pi to simulate multiple TV channels with shows and commercials. You can set up different channels, schedule shows, and even add seasonal content. The system supports multiple channels playing at the same time and can automatically insert commercials. This project is great for people who miss the old TV experience and want to relive it with a nostalgic feel. It requires some technical setup but offers a fun way to enjoy retro TV.
https://github.com/shane-mason/FieldStation42
#python
The Jelly Evolution Simulator is a program that lets you watch jelly-like creatures evolve over time. You can run it using a simple command in Python. The simulator allows you to control various features like closing the program, toggling markers, storing species, and changing colors. It also lets you scroll through different generations to see how the creatures change. This tool is useful for understanding how evolution works in a fun and interactive way. It helps users visualize how small changes can lead to different outcomes over time.
https://github.com/carykh/jes
Version 3.10 of the legendary programming language is now here: https://www.python.org/downloads/release/python-3100
No rush to update, though. #Python
#python
Our internet is broken again, and this time by Python setuptools.
[BUG] Version 78.0.1 breaks install of ansible-vault package · Issue #4910 · pypa/setuptools
https://github.com/pypa/setuptools/issues/4910
#Python is the main language of data science, per this analysis on 10M Jupyter Notebooks: https://blog.jetbrains.com/datalore/2020/12/17/we-downloaded-10-000-000-jupyter-notebooks-from-github-this-is-what-we-learned/
#python
I had the wrong idea for a long time that IDEs treat method/function without return type hint as returning None type.
I was wrong. In PEP484, it says IDE should treat such a method/function as a type that is as general as possible. Ah that just makes sense.
https://peps.python.org/pep-0484/#the-meaning-of-annotations
#python
This post is a retro on how I learned Python.
Disclaimer: I can not claim that I am a master of Python. This post is a retrospective of how I learned Python in different stages.
I started using Python back in 2012. Before this, I was mostly a Matlab/C user.
Python is easy to get started, yet it is hard to master. People coming from other languages can easily make it work but will write some "disgusting" python code. And this is because Python people talk about "pythonic" all the time. Instead of being an actual style guide, it is rather a philosophy of styles.
When we get started, we are most likely not interested in [PEP8](https://peps.python.org/pep-0008/) and [PEP257](https://peps.python.org/pep-0257/). Instead, we focus on making things work. After some lectures from the university (or whatever sources), we started to get some sense of styles. Following these lectures, people will probably write code and use Python in some projects. Then we began to realize that Python is strange, sometimes even doesn't make sense. Then we started leaning about the philosophy behind it. At some point, we will get some peer reviews and probably fight against each other on some philosophies we accumulated throughout the years.
The attached drawing (in comments) somehow captures this path that I went through. It is not a monotonic path of any sort. This path is most likely to be permutation invariant and cyclic. But the bottom line is that mastering Python requires a lot of struggle, fights, and relearning. And one of the most effective methods is peer review, just as in any other learning task in our life.
Peer review makes us think, and it is very important to find some good reviewers. Don't just stay in a silo and admire our own code. To me, the whole journey helped me building one of the most important philosophies of my life: embrace open source and collaborate.