Maintaining aging Python codebases is a notorious balancing act. Legacy code written in the pre-type-hinting era frequently conceals silent type mismatches that only surface under heavy production traffic. At the same time, manually writing exhaustive parameter tables for unit tests is tedious and often cut short under sprint deadlines, leaving critical edge cases unverified.
JetBrains AI brings language models directly into PyCharm's native compiler structures. Instead of operating purely as a text prediction tool like disconnected chatbots, JetBrains AI combines LLMs with PyCharm's Abstract Syntax Tree (AST), local symbol index, and control-flow graph. At 365Finds, our research indicates that using JetBrains AI Assistant to execute a two-step cycle—first inferring rigorous PEP 484 type annotations and then deriving parameterized Pytest matrices—delivers vastly superior code safety compared to generating tests from untyped, dynamic code.
Here is the operational blueprint for modernizing Python modules with JetBrains AI in PyCharm.
1. Why Untyped Python Breaks AI Test Generation
When developers prompt general-purpose AI tools to generate tests for untyped Python functions, the models must guess argument structures. Without concrete type declarations, LLMs routinely introduce fabricated assertions, miss subtle NoneType edge conditions, or generate invalid inputs that skew test metrics.
PyCharm's static analysis engine natively detects type anomalies through its internal inspections (such as PyTypeChecker and PyUnresolvedReferences). When JetBrains AI is invoked, it draws upon this syntactic index. Establishing explicit PEP 484 annotations first grounds the IDE's semantic understanding. Once the function signature is typed, downstream test generators have strict structural boundaries to target, turning fuzzy test guessing into a deterministic test matrix.
2. Inferring PEP 484 Type Hints and Docstrings via AI Actions
Consider a legacy data transformation function that processes e-commerce orders without any type hints:
# legacy_order.py - Legacy dynamic Python code
def process_order_discount(order_data, discount_rate, currency="USD"):
if not order_data:
raise ValueError("Empty order data")
items = order_data.get("items", [])
subtotal = sum(item.get("price", 0.0) * item.get("quantity", 1) for item in items)
if discount_rate < 0.0 or discount_rate > 1.0:
raise ValueError("Invalid discount rate")
discounted = subtotal * (1.0 - discount_rate)
return {
"subtotal": float(subtotal),
"discounted": round(discounted, 2),
"currency": currency,
}
Step-by-Step Type Inference Workflow
- Position the Caret: Place your cursor directly on the function signature
def process_order_discount(...). - Trigger AI Actions: Press
Alt + Enter(or⌥ + Enteron macOS) and navigate to AI Actions | Add Type Hints (or use the floating AI toolbar). - Context Analysis: JetBrains AI inspects internal operations (
.get("items", []), arithmetic operations onpriceandquantity, and dictionary return keys) alongside call sites across your project. - Prompt Refinement (Optional): If your project enforces modern Python syntax (Python 3.10+ union pipes
|andtyping.TypedDict), open the prompt input in the AI popup or AI Chat and specify:"Infer PEP 484 type annotations using modern typing.TypedDict for dictionary structures and add a Google-style docstring including argument types, return values, and raised exceptions."
- In-Editor Review: PyCharm renders an in-editor diff highlighting suggested additions. Review the inferred types and hit Enter or click Accept to apply them.
The resulting modernized code establishes full type safety:
# Modernized with PEP 484 annotations and Google-style docstring
from typing import TypedDict, Any
class OrderItem(TypedDict):
price: float
quantity: int
class OrderData(TypedDict):
items: list[OrderItem]
class ProcessedOrderResult(TypedDict):
subtotal: float
discounted: float
currency: str
def process_order_discount(
order_data: OrderData | dict[str, Any],
discount_rate: float,
currency: str = "USD",
) -> ProcessedOrderResult:
"""Calculate the subtotal and discounted total for a given order.
Args:
order_data: Dictionary containing order items with price and quantity.
discount_rate: Discount rate between 0.0 and 1.0.
currency: ISO currency code, defaults to "USD".
Returns:
ProcessedOrderResult containing subtotal, discounted total, and currency.
Raises:
ValueError: If order_data is empty or discount_rate is out of bounds.
"""
if not order_data:
raise ValueError("Empty order data")
items = order_data.get("items", [])
subtotal = sum(item.get("price", 0.0) * item.get("quantity", 1) for item in items)
if discount_rate < 0.0 or discount_rate > 1.0:
raise ValueError("Invalid discount rate")
discounted = subtotal * (1.0 - discount_rate)
return {
"subtotal": float(subtotal),
"discounted": round(discounted, 2),
"currency": currency,
}
Applying these annotations immediately clears PyCharm's inspection warnings and provides upstream callers with rich autocompletion hints.
3. Generating Parameterized Pytest Suites
With explicit types and error conditions defined, generating comprehensive unit tests becomes structured and predictable.
Configuring Pytest in PyCharm
Before triggering generation, confirm that Pytest is configured as your primary test runner:
- Open Settings:
Ctrl + Alt + S(macOS:⌘ + ,). - Go to Tools | Python Integrated Tools.
- Under Testing, ensure Default test runner is set to pytest.
Executing AI Test Generation
- Trigger Test Generation: Place the caret inside
process_order_discount, pressAlt + Enter, and select AI Actions | Generate Unit Tests. - Review in AI Diff Tab: PyCharm automatically opens a dedicated AI Diff tab showing candidate test implementations alongside your project tree.
- Refine with "Specify": PyCharm's test generator allows interactive prompt refinement. Click the Specify button and provide exact parameterized test criteria:
"Generate a comprehensive pytest suite. Utilize
@pytest.fixturefor reusable mock orders. Implement@pytest.mark.parametrizefor valid calculation permutations (including zero discount, standard percentage, full discount, and custom currency). Include a separate parameterized test for exception handling covering empty inputs and boundary violation rates withpytest.raises." - Inspect and Accept: Review the proposed diff in the editor. Once satisfied, click Accept all. PyCharm saves the test suite into your configured
tests/directory (e.g.,test_order.py) and resolves module imports.
Here is the generated test suite:
import pytest
from legacy_order import process_order_discount, OrderData
@pytest.fixture
def sample_standard_order() -> OrderData:
"""Fixture providing a standard order payload."""
return {
"items": [
{"price": 100.0, "quantity": 2},
{"price": 50.0, "quantity": 1},
]
}
@pytest.mark.parametrize(
"discount_rate, currency, expected_subtotal, expected_discounted",
[
(0.0, "USD", 250.0, 250.0), # Boundary: No discount
(0.1, "USD", 250.0, 225.0), # Standard: 10% discount
(0.5, "EUR", 250.0, 125.0), # Standard: 50% discount with non-default currency
(1.0, "USD", 250.0, 0.0), # Boundary: 100% discount
],
)
def test_process_order_discount_valid(
sample_standard_order: OrderData,
discount_rate: float,
currency: str,
expected_subtotal: float,
expected_discounted: float,
) -> None:
"""Verify calculation correctness across standard and boundary discount rates."""
result = process_order_discount(sample_standard_order, discount_rate, currency=currency)
assert result["subtotal"] == expected_subtotal
assert result["discounted"] == expected_discounted
assert result["currency"] == currency
@pytest.mark.parametrize(
"invalid_order, invalid_rate, expected_error_msg",
[
({}, 0.1, "Empty order data"),
(None, 0.1, "Empty order data"),
({"items": [{"price": 10.0, "quantity": 1}]}, -0.05, "Invalid discount rate"),
({"items": [{"price": 10.0, "quantity": 1}]}, 1.05, "Invalid discount rate"),
],
)
def test_process_order_discount_exceptions(
invalid_order: OrderData | None,
invalid_rate: float,
expected_error_msg: str,
) -> None:
"""Verify proper exception raising for boundary violations and invalid inputs."""
with pytest.raises(ValueError, match=expected_error_msg):
process_order_discount(invalid_order, invalid_rate) # type: ignore[arg-type]
Executing and Reviewing in PyCharm
Click the gutter run icon next to test_process_order_discount_valid or press Ctrl + Shift + F10 (macOS: ⌃ + ⇧ + R). PyCharm launches the Pytest runner window, unrolling every parameterized iteration as an individual node. If an assertion fails, PyCharm's integrated test tool window provides a rich visual diff comparing expected and actual dictionary entries.
4. Comparing JetBrains AI Assistant to Generic Copilots
| Capability | JetBrains AI in PyCharm | Generic Code Chatbots / Copilots |
|---|---|---|
| Semantic Context | Combines AST, symbol table, and call graphs; aware of project imports | Limited to active buffer and recent tab text |
| Type Enforcement | Validates suggested hints against built-in PEP 484 inspections instantly | Emits guesses; unaware if types conflict with local stubs |
| Test Integration | Opens code directly in PyCharm's AI Diff tab; routes to default test runner | Generates loose code snippets requiring manual copy-pasting |
| Review Workflow | Inline patch acceptance, single-click gutter reverts, in-editor conflict checks | External editor diffs or manual overwrite |
5. 365Finds Research Verdict and Engineering Recommendations
365Finds strongly advocates for adopting JetBrains AI Assistant as a standard pipeline tool for Python refactoring, subject to two strategic constraints:
- Always Type Before Testing: Never ask JetBrains AI to generate unit tests for unannotated functions. First, use
AI Actions | Add Type Hintsto let PyCharm index the data structures. The accuracy and edge-case quality of generated Pytest suites improves dramatically when built on concrete types. - Scrutinize Dynamic Metaprogramming: JetBrains AI shines across standard Python business logic, API models, and data transformation scripts. However, when refactoring dynamic decorators,
getattrreflection, or complex ORM metaclasses, the assistant can fall back to genericAnytypes. In these scenarios, usetyping.Protocolor custom stubs to guide the AI rather than accepting default proposals blindly.
By pairing PyCharm's decade-long investment in Python static analysis with JetBrains AI, engineering teams can systematically modernize legacy codebases while building rock-solid, parameterized test coverage in a fraction of the traditional manual time.