--- title: "AST Black Magic: Run synchronous Python code on asynchronous Pyodide - Yuichiro Tachibana" tags: PyConTW2025, 2025-organize, 2025-共筆 --- # AST Black Magic: Run synchronous Python code on asynchronous Pyodide - Yuichiro Tachibana {%hackmd L_RLmFdeSD--CldirtUhCw %} <iframe src=https://app.sli.do/event/jzFDejDjxtRCfR6sRzRnjN height=450 width=100%></iframe> :::success 本演講提供 AI 翻譯字幕及摘要,請點選這裡前往 >> [PyCon Taiwan AI Notebook](https://pycontw.connyaku.app/?room=tkP9aQefWTFcsrvwmby4) AI translation subtitles and summaries are available for this talk. Click here to access >> [PyCon Taiwan AI Notebook](https://pycontw.connyaku.app/?room=tkP9aQefWTFcsrvwmby4) ::: > Collaborative writing start from below > 從這裡開始共筆 ## Anout the presenter - Software Artisan / Indie Dev / OSS Enthusiast - ML Developer Advocate at Hugging Face - Stramlit Creator - [whitphx.info](https://www.whitphx.info/) ## AST - AST (Abstract Syntax Tree) in Python is a tree representation of the parsed source code structure. - The behavior of a source code can be modified with AST without modifying the source code itself ### Applications of AST - Linter - Code Analysis - Code Refactoring ## Pyodide - Python in javascript ### Issues - Executes Python code in WebAssembly, which has a different nature than our usual environment - Single-threaded - Browser's event loop - some Python features do not work as expected - This talk focus on asynchronous method |Not working in pyodide| Should use| |:--|:--| |`asyncio.run(fn())`|`await fn()`| |`time.sleep(1)`|`await asyncio.sleep(1)`| ### Motivation - We don't want to rewrite the code - Should be able to run inside pyodide if it can be used in usual python - Using AST for this #### Simple Solution ```python= # parse time.sleep and # transform to await asyncio.sleep ``` **Issue**: What if the function to be modified locates inside another function? --> Custom Name Resolution #### Name Resolution **Issue**: - Chain reaction - File overwrite key functions - Dynamic behavior - --> Determine the line we're going to support #### Give up ## Summary - AST-based approach - can achieve syntax-level code modification - has limitations Below is the part that speaker updated the talk/tutorial after speech 講者於演講後有更新或勘誤投影片的部份