Pewarta Proxy

📋 Server Request & Proxy Logs

Loading active proxy settings...
Developed by Khairul Adha (adhexa.id)
Mengambil log server...

⚙️ Pengaturan Proxy Target

A person with a clipboard feeds tangled code into a machine labeled Smells, where an AI arm works one step at a time past passing tests into a Clean tray.

How to Refactor Python Code With an AI Agent

Say you have a Python project that works, and nobody is filing bug reports for it. However, every change, fix, or new feature takes longer than it should and requires working on multiple files. Also, you try to avoid touching certain files because small changes there break the whole project. That’s called technical debt, and you can pay it down when you refactor Python code with AI.

Refactoring improves the code’s structure without changing what it does. This way, the next change will cost less than it would have before refactoring.

An AI coding agent can help you pay down technical debt faster. It takes on the tedious parts, like reading every module in search of code smells and rewriting the code, while you stay in charge of what changes. The test suite confirms that each change keeps the code’s behavior, so you can review every step.

In this guide, you’ll refactor a command-line to-do app built with Typer. You’ll use an AI agent to diagnose the code, plan the refactorings, check that tests pin the current behavior, and apply one refactoring at a time, keeping only the changes that pass the tests, produce no new tool errors, and pass your review:

Diagnose smells, verify the plan, and pin behavior with tests. Then prompt, run the gate, and review the diff to commit or reset.
The AI-Assisted Refactoring Loop

Before you start, make sure you have everything you need to follow along. Download the sample project you’ll use by clicking the link below:

Take the Quiz: Test your knowledge with our interactive “How to Refactor Python Code With an AI Agent” quiz. You’ll receive a score upon completion to help you track your learning progress:


Interactive Quiz

How to Refactor Python Code With an AI Agent

Check how well you can refactor Python code with an AI agent, from a verified plan and characterization tests to a quality gate on every change.

Prerequisites

This tutorial assumes that you’re comfortable with Python and a few everyday developer tools. To get the most out of it, you should have the following in place:

  • Python 3.10 or newer: You can use a newer version like 3.15, but nothing in the sample project needs it.
  • Testing with pytest: You should be familiar with pytest, which runs the sample project’s test suite.
  • Basic Git: You’ll use version control with Git as your safety net and commits as the unit of review in this tutorial.
  • The uv package manager: You’ll use uv to install the sample project and run its tools. If you don’t have it yet, follow the installation instructions.
  • A project-aware AI coding agent: This guide uses Claude Code to illustrate the workflow. The process works with any AI agent that can read your files and run commands.
  • The sample project: You’ll refactor the to-do app from the sample project that you downloaded above.

The download includes two ZIP files. The ai-refactor-python-starter.zip file holds the starter project, which includes the app’s code, a test suite, an agent skill, and the development tools you’ll use throughout this tutorial.

The ai-refactor-python-final.zip file holds the finished project, which includes the refactoring plan, the tool settings, and the code after every refactoring. Use it to compare your results with the ones in this tutorial.

Ruff, Radon, mypy, and Coverage.py are part of the development tools. However, you don’t need any experience with them because you’ll walk through the few settings this workflow relies on.

Step 1: Set Up Your Project for AI-Assisted Refactoring

Before you start refactoring your codebase, you need to set up the target project so the agent can work in it. You also need to install dependencies and the tools. In this step, you’ll get the sample project, configure the code quality tools, put the project under version control, and review the rules that guide the agent.

Get the Sample Project

To get started, unzip ai-refactor-python-starter.zip into a working directory. You’ll get the following project structure:

ai-refactor-python-starter/
│
├── .claude/
│   │
│   └── skills/
│       │
│       └── refactor-plan/
│           │
│           ├── assets/
│           │   └── REFACTOR-template.md
│           │
│           ├── references/
│           │   └── code-smells.md
│           │
│           └── SKILL.md
│
├── rptodo/
│   ├── __init__.py
│   ├── __main__.py
│   ├── cli.py
│   ├── config.py
│   ├── database.py
│   └── rptodo.py
│
├── tests/
│   ├── __init__.py
│   ├── test_cli.py
│   ├── test_config.py
│   ├── test_database.py
│   └── test_rptodo.py
│
├── .gitignore
├── AGENTS.md
├── CLAUDE.md
├── pyproject.toml
└── uv.lock

The rptodo/ package is the to-do app exactly as published. The tests/ folder has one test file for each of the four modules that hold the app’s logic. Together, they pin down how the app behaves today, including a few bugs. The .claude/skills/refactor-plan/ folder holds an agent skill that you’ll use to look for code smells with the help of your agent.

Inside rptodo/, each module has one job:

  • cli.py defines the Typer commands and prints their results.
  • rptodo.py holds the Todoer class, which adds, completes, and removes to-dos.
  • database.py reads and writes the JSON database file.
  • config.py creates config.ini, which stores the path to the database.
  • __init__.py defines the error codes and their messages.

For example, rptodo complete 1 runs set_done() in cli.py, which calls Todoer.set_done(). Todoer then reads and writes the to-dos through DatabaseHandler in database.py.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Article

Already a member? Sign-In

Locked learning resources

The full article is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Article

Already a member? Sign-In

About Leodanis Pozo Ramos

Leodanis is a self-taught Python developer, educator, and technical writer with over 10 years of experience.

» More about Leodanis

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal.


Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!

Become a Member to join the conversation.

Keep Learning

Related Topics: intermediate ai tools