AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

How Do Python Developers Use JetBrains AI Assistant in PyCharm to Infer Type Hints and Generate Parameterized Pytest Suites?

平沼慧一 · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

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

  1. Position the Caret: Place your cursor directly on the function signature def process_order_discount(...).
  2. Trigger AI Actions: Press Alt + Enter (or ⌥ + Enter on macOS) and navigate to AI Actions | Add Type Hints (or use the floating AI toolbar).
  3. Context Analysis: JetBrains AI inspects internal operations (.get("items", []), arithmetic operations on price and quantity, and dictionary return keys) alongside call sites across your project.
  4. Prompt Refinement (Optional): If your project enforces modern Python syntax (Python 3.10+ union pipes | and typing.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."

  5. 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:

Executing AI Test Generation

  1. Trigger Test Generation: Place the caret inside process_order_discount, press Alt + Enter, and select AI Actions | Generate Unit Tests.
  2. Review in AI Diff Tab: PyCharm automatically opens a dedicated AI Diff tab showing candidate test implementations alongside your project tree.
  3. 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.fixture for reusable mock orders. Implement @pytest.mark.parametrize for 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 with pytest.raises."

  4. 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

CapabilityJetBrains AI in PyCharmGeneric Code Chatbots / Copilots
Semantic ContextCombines AST, symbol table, and call graphs; aware of project importsLimited to active buffer and recent tab text
Type EnforcementValidates suggested hints against built-in PEP 484 inspections instantlyEmits guesses; unaware if types conflict with local stubs
Test IntegrationOpens code directly in PyCharm's AI Diff tab; routes to default test runnerGenerates loose code snippets requiring manual copy-pasting
Review WorkflowInline patch acceptance, single-click gutter reverts, in-editor conflict checksExternal 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:

  1. Always Type Before Testing: Never ask JetBrains AI to generate unit tests for unannotated functions. First, use AI Actions | Add Type Hints to let PyCharm index the data structures. The accuracy and edge-case quality of generated Pytest suites improves dramatically when built on concrete types.
  2. Scrutinize Dynamic Metaprogramming: JetBrains AI shines across standard Python business logic, API models, and data transformation scripts. However, when refactoring dynamic decorators, getattr reflection, or complex ORM metaclasses, the assistant can fall back to generic Any types. In these scenarios, use typing.Protocol or 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.


References