NeurIPS 2026Coming to NeurIPS?Explore papers, orals & directions

Refactoring to Pythonic Idioms: A Hybrid Knowledge-Driven Approach Leveraging Large Language Models

Zejun Zhang, Zhenchang Xing, Xiaoxue Ren, Qinghua Lu, Xiwei Xu

This paper presents a novel way to bridge the gap between "standard" Python and "Pythonic" code—the idiomatic, concise, and efficient style favored by the community. While Pythonic idioms like list comprehensions or with statements are powerful, they are often underutilized or implemented incorrectly.

TL;DR

The authors propose a hybrid refactoring approach that combines the deterministic precision of rule-based systems with the creative adaptability of Large Language Models (LLMs). By using LLMs to generate "Analytic Rule Interfaces" (ARIs) that analyze code structure, their system achieves over 90% accuracy and F1-score across 13 different Pythonic idioms, significantly outperforming both pure rule-based and pure LLM-based methods.

What Problem Does This Paper Address?

Writing "Pythonic" code is harder than it looks. Even experienced developers often miss opportunities to use idioms, leading to "non-idiomatic" code that is more verbose and potentially slower.

Existing automated refactoring tools generally fall into two camps, both of which have flaws:

  1. Rule-based approaches (e.g., RIdiom): These use rigid, human-defined rules. They are precise but "brittle"—they often miss code that doesn't perfectly match a template (Code Miss) or struggle with complex logic.
  2. LLM-only approaches: While LLMs are great at understanding intent, they are "black boxes." They can hallucinate, miss subtle context, or suggest refactorings that actually break the code's logic (Wrong Refactoring).

The authors aim to solve three specific challenges: Code Miss (missing refactorable code), Wrong Detection (flagging code that shouldn't be changed), and Wrong Refactoring (producing incorrect idiomatic code).

Methods

The core of the paper is a three-module hybrid framework that uses LLMs not just to write code, but to build the tools to analyze code.

  1. Knowledge Module: Instead of hard-coding rules, the authors define idioms using three elements: the ASTscenario (the context), the ASTcomponent (the specific code structure), and the Condition (the logic required for refactoring). They then prompt an LLM to generate Python functions called Analytic Rule Interfaces (ARIs). These ARIs are deterministic scripts that can extract and verify these elements from an Abstract Syntax Tree (AST).
  2. Extraction Module: This module uses the generated ARIs to scan a project. Because it uses code-based rules to find candidates, it avoids the "randomness" of asking an LLM to find bugs directly.
  3. Idiomatization Module: Once a candidate is found, the system performs a three-step "sandwich" refactoring:
  4. Abstraction: It replaces specific variable names with generic symbols (e.g., v1, v2). This prevents the LLM from getting distracted by domain-specific names.
  5. Idiomatization: The LLM refactors the abstract code.
  6. Rewriting: ARIs are used to map the generic symbols back to the original variable names, ensuring the final code fits perfectly into the original source.

Datasets

The researchers evaluated their approach using two primary benchmarks:

  • Established Idioms: A dataset of 3,311 methods (4,678 code pairs) sampled from the RIdiom dataset, covering 9 common idioms like list-comprehension, truth-test, and loop-else.
  • New Idioms: To test scalability, they introduced a new benchmark of 600 methods (1,008 code pairs) for 4 idioms not covered by previous tools: with, enumerate, fstring, and chain-assign-same-value.
  • Verification: All ground-truth labels were manually verified by 18 external workers with significant Python experience to ensure accuracy.

Key Insights and Ideas

  • LLMs as Tool-Builders: The most clever insight is using LLMs to generate the ARIs. This turns a stochastic LLM into a deterministic rule-generator. Once the ARI is verified, it works with 100% consistency, unlike a prompt.
  • The Power of Abstraction: By stripping away variable names before refactoring, the authors found that LLMs become much more reliable. It forces the model to focus on the structural logic of the idiom rather than the semantics of the specific project.
  • Hybrid Strength: The results show that rules are best for "where" (detection), while LLMs are best for "how" (transformation). By separating these tasks, the system minimizes the weaknesses of both.

Key Results

The hybrid approach, dubbed "RIdiom+" (implied), consistently outperformed the baselines:

  • Superior Performance: Across 9 established idioms, the approach maintained Accuracy, F1-score, and Recall above 90%.
  • Beating the Baselines: In many cases, the pure LLM approach (Prompt-LLM) had a recall below 10% for complex idioms like star-in-func-call, whereas the hybrid approach stayed above 95%.
  • Scalability: On the 4 new idioms where the previous state-of-the-art (RIdiom) couldn't function at all, the hybrid approach achieved metrics consistently exceeding 90%.

Limitations and Future Work

  • Syntax Dependency: The current system relies on generating an AST, meaning it can only process code that is already syntactically correct. It cannot yet help with "broken" code.
  • Readability vs. Idioms: The authors acknowledge that being "Pythonic" isn't always better if it makes the code harder for a specific team to read. They suggest future versions could include LLM-generated comments explaining the benefits of the refactoring.
  • Automation: While the ARI generation is prompted, the initial definition of the "three elements" (scenario, component, condition) still requires some human insight. Future work aims to automate the discovery of these elements for new idioms.

Summary updated

BibTeX
@inproceedings{zhang2024refactoring,
  author = {Zejun Zhang and Zhenchang Xing and Xiaoxue Ren and Qinghua Lu and Xiwei Xu},
  title = {{Refactoring to Pythonic Idioms: A Hybrid Knowledge-Driven Approach Leveraging Large Language Models}},
  booktitle = {Proc. ACM Softw. Eng},
  year = {2024},
  url = {https://openreview.net/forum?id=K4SLR8kfVL},
}
Figure