Python 3.11+ Modernization

VerifiedSafe

Applies Python 3.11+ modernization patterns including PEP 585/604 type hints, match-case, walrus operator, and Self type. Use when reviewing existing code for legacy patterns or writing new code to ensure modern idioms. Supports analyzing specific files or explaining individual topics.

Sby Skills Guide Bot
DevelopmentIntermediate
6/2/2026
Claude Code
#python#type-hints#modern-patterns#pytest

Recommended for

Automated summary

Applies modern Python 3.11+ idioms including type hints, walrus operator, match-case, Self type, and pytest-mock patterns to code review, writing, and refactoring tasks.

Strengths

  • Enforces up-to-date Python practices.
  • Provides concrete before/after examples.
  • Covers type hints, testing, and CLI frameworks.
  • Reduces boilerplate with modern syntax.

Limitations

  • Requires Python 3.11+ environment.
  • May not apply to legacy codebases that cannot upgrade.
  • Focuses on syntax patterns, not architectural design.
When to use it

Use when writing new Python code, reviewing pull requests for modernization opportunities, or refactoring legacy Python code to adopt current idioms.

When not to use it

Do not use for projects that must maintain compatibility with Python versions below 3.11, or when the team is not familiar with modern Python features.

Security analysis

Safe
Quality score90/100

The skill is purely advisory, providing guidance on Python code modernization. It only reads files and suggests changes without executing any commands or performing network operations. There is no risk of destructive or exfiltrating actions.

No concerns found

How this analysis is made

Examples

Modernize a specific file
Modernize the Python code in 'src/utils.py' using Python 3.11+ patterns.
Explain a modern pattern
Explain how to use the Self type (PEP 673) in Python with before/after examples.
Refactor legacy patterns
Refactor this code to use modern Python: from typing import List; names: List[str] = ['a', 'b']

name: modernpython description: Apply modern Python 3.11+ best practices with proper types, DRY, SRP, and framework patterns. Use when reviewing Python code for modernization opportunities, when writing new Python code to ensure modern patterns, or when refactoring legacy Python code to use current idioms. user-invocable: true argument-hint: "[file-paths-or-topic]"

Python Modernization Guide

The model applies modern Python 3.11+ patterns when writing or reviewing Python code.

Arguments

$ARGUMENTS

Instructions

If file paths provided:

  1. Read each file
  2. Identify legacy patterns
  3. Apply modern transformations from the reference guide
  4. Report changes made or recommended

If topic provided (e.g., "typing", "match-case"):

  1. Provide guidance on that specific topic
  2. Show before/after examples

If no arguments:

  1. Ask what code to review or what topic to explain

Quick Reference: Modern Patterns

Type Hints (PEP 585, 604)

# Legacy (NEVER use)
from typing import List, Dict, Optional, Union

# Modern (ALWAYS use)
items: list[str]
config: dict[str, int] | None
value: int | str

Walrus Operator (PEP 572)

# Legacy
data = fetch_data()
if data:
    process(data)

# Modern
if data := fetch_data():
    process(data)

Match-Case (PEP 634)

Use match-case when using elif. Use if/elif only for inequalities or boolean operators.

# Modern (for any elif pattern)
match status_code:
    case 200: return "OK"
    case 404: return "Not Found"
    case _: return "Unknown"

Self Type (PEP 673)

from typing import Self

class Builder:
    def add(self, x: int) -> Self:
        self.value += x
        return self

Exception Notes (PEP 678)

except FileNotFoundError as e:
    e.add_note(f"Attempted path: {path}")
    raise

StrEnum (Python 3.11+)

from enum import StrEnum

class Status(StrEnum):
    PENDING = "pending"
    RUNNING = "running"

TOML Support (Python 3.11+)

import tomllib
from pathlib import Path

config = tomllib.load(Path("pyproject.toml").open("rb"))

Testing Patterns

ALWAYS use pytest-mock, NEVER unittest.mock:

# Legacy (NEVER use)
from unittest.mock import Mock, patch

# Modern (ALWAYS use)
from pytest_mock import MockerFixture

def test_feature(mocker: MockerFixture) -> None:
    mock_func = mocker.patch('module.function', return_value=42)

Framework Patterns

Typer CLI

ALWAYS use Annotated syntax:

from typing import Annotated
import typer

@app.command()
def process(
    input_file: Annotated[Path, typer.Argument(help="Input file")],
    verbose: Annotated[bool, typer.Option("--verbose", "-v")] = False,
) -> None:
    """Process input file."""
    pass

Rich Tables

Use explicit width control for production CLIs:

from rich.console import Console
from rich.table import Table
from rich.measure import Measurement

def _get_table_width(table: Table) -> int:
    temp_console = Console(width=9999)
    measurement = Measurement.get(temp_console, temp_console.options, table)
    return int(measurement.maximum)

Detailed Reference

For complete transformation rules, PEP references, and framework patterns, see:

Complete Modernization Guide


Core Principles

  1. Use Python 3.11+ as minimum baseline
  2. Leverage built-in generics (PEP 585) and pipe unions (PEP 604) exclusively
  3. Apply walrus operator to reduce line count
  4. Use match-case for elif patterns
  5. Implement comprehensive type hints with Protocol, TypeVar, TypeGuard
  6. Use Self type (PEP 673) for fluent APIs
  7. Follow Typer patterns with Annotated syntax for CLIs
  8. Use Rich for terminal output with proper width handling
  9. Write pytest tests with pytest-mock and AAA pattern
  10. Apply clean architecture with dependency injection

References

From the file to a first result

The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.

View the source and supporting files

This download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.

1. Download the file

Download SKILL.md

From the root of a test project, save the file as .skill-downloads/python-3-11-modernization-mmh8qrn2/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.

Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.

mkdir -p '.skill-downloads/python-3-11-modernization-mmh8qrn2' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/python-3-11-modernization-mmh8qrn2/download' --output '.skill-downloads/python-3-11-modernization-mmh8qrn2/SKILL.md.part' && mv '.skill-downloads/python-3-11-modernization-mmh8qrn2/SKILL.md.part' '.skill-downloads/python-3-11-modernization-mmh8qrn2/SKILL.md'

2. Check prerequisites

Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.

Original excerpt: Quick Reference: Modern Patterns

Type Hints (PEP 585, 604)

# Legacy (NEVER use)
from typing import List, Dict, Optional, Union

# Modern (ALWAYS use)
items: list[str]
config: dict[str, int] | None
value: int | str

Walrus Operator (PEP 572)

# Legacy
data = fetch_data()
if data:
    process(data)

# Modern
if data := fetch_data():
    process(data)

Match-Case (PEP 634)

Use match-case when using elif. Use if/elif only for inequalities or boolean operators.

# Modern (for any elif pattern)
match status_code:
    case 200: return "OK"
    case 404: return "Not Found"
    case _: return "Unknown"

Self Type (PEP 673)

from typing import Self

class Builder:
    def add(self, x: int) -> Self:
        self.value += x
        return self

Exception Notes (PEP 678)

except FileNotFoundError as e:
    e.add_note(f"Attempted path: {path}")
    raise

StrEnum (Python 3.11+)

from enum import StrEnum

class Status(StrEnum):
    PENDING = "pending"
    RUNNING = "running"

TOML Support (Python 3.11+)

import tomllib
from pathlib import Path

config = tomllib.load(Path("pyproject.toml").open("rb"))

The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.

3. Load the skill

After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.

Claude Code
test -f '.skill-downloads/python-3-11-modernization-mmh8qrn2/SKILL.md' && test -s '.skill-downloads/python-3-11-modernization-mmh8qrn2/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/modernpython' && cp -R '.skill-downloads/python-3-11-modernization-mmh8qrn2' '.claude/skills/modernpython'

OpenSkills

OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.

Official OpenSkills installation
openskills install './.skill-downloads/python-3-11-modernization-mmh8qrn2'

openskills read 'python-3-11-modernization-mmh8qrn2'

Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.

For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.

openskills sync

Manual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.

4. Try a first task

Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:

Read .skill-downloads/python-3-11-modernization-mmh8qrn2/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.

Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.

Related skills