Skill

Generate Pythonic Code with Modern Features

Skill for modern Python 3.10+ - type hints, pattern matching, dataclasses, async code, and pyproject.toml tooling.

Works with poetrypdmblackruffmypy

Maintainer of this project? Claim this page to edit the listing.


91
Spark score
out of 100
Updated 7 months ago
Version 1.0.0
Models

Add to Favorites

Why it matters

Leverage expert Python development practices to generate clean, efficient, and maintainable Python code. This asset ensures adherence to modern standards like type hints, PEP 8, and pattern matching.

Outcomes

What it gets done

01

Write Python code with type hints and PEP 8 compliance.

02

Utilize modern Python features like pattern matching and data classes.

03

Implement context managers and robust error handling.

04

Generate asynchronous code using async/await.

Install

Add it to your toolbox

Run in your project directory:

curl -fsSL https://spark.entire.vc/get/vb-python-developer | bash

Overview

Python Developer

A skill for modern Python 3.10+ development - type hints, structural pattern matching, dataclasses, context managers, async/await, and pyproject.toml tooling configuration. Use it for modern Python idioms and tooling specifically, not as a beginner Python tutorial.

What it does

This skill provides expert-level guidance for modern Python development practices - type hints, PEP 8 style, idiomatic Pythonic code, and properly formatted docstrings in Google or NumPy style. Modern Python features covered: type hints for Python 3.10+ (function signatures with built-in generics like list[dict[str, Any]], and the | union-type syntax), structural pattern matching (match/case on list patterns including wildcard and rest captures), and data classes:

from dataclasses import dataclass, field
from datetime import datetime

@dataclass
class User:
    id: int
    name: str
    email: str
    created_at: datetime = field(default_factory=datetime.now)
    roles: list[str] = field(default_factory=list)

The pattern-matching guidance is shown against a command-dispatch example:

match command:
    case ["quit"]:
        return "Goodbye!"
    case ["load", filename]:
        return load_file(filename)
    case ["save", filename, *options]:
        return save_file(filename, options)
    case _:
        return "Unknown command"

Best practices cover context managers (@contextmanager wrapping resource acquisition and release in a try/finally), error handling (a custom exception class carrying a message and code, and catching specific exception types like ValueError/IOError rather than a bare except), and async/await (an aiohttp-based async fetch function and an AsyncGenerator-based streaming function). Project structure follows a src/-layout convention (a package directory with core/, services/, utils/ subpackages, a tests/ directory, and pyproject.toml at the project root), configured via pyproject.toml for tools like Poetry or PDM, with example configuration sections for Black (88-char line length), Ruff (88-char line length, selected lint rule codes E, F, I, N, W), and mypy (strict mode enabled).

When to use - and when NOT to

Use it when writing or reviewing modern Python code - applying type hints, pattern matching, dataclasses, async code, or setting up pyproject.toml tooling. It is not a beginner Python tutorial - it assumes familiarity with the language and focuses on modern (3.10+) idioms and tooling.

Inputs and outputs

Given a Python code-design question, it produces type-hinted signatures such as def greet(name: str) -> str, def process(data: list[dict[str, Any]]) -> dict[str, int], and a str | int | None union-typed parse function, alongside pattern-matching logic, dataclasses, context managers, async functions, or a pyproject.toml configuration block covering Black, Ruff, and mypy sections.

Who it's for

Python developers already comfortable with the language's basics who need to apply Python 3.10+ idioms - type hints, pattern matching, dataclasses, async code - and set up matching pyproject.toml tooling, rather than developers looking to learn Python from scratch.

Source README

You are an expert Python developer with comprehensive knowledge of modern Python development practices.

Core Principles

  • Type Hints: Always use type hints for function signatures and class attributes
  • PEP 8: Follow PEP 8 style guidelines consistently
  • Pythonic Code: Write idiomatic Python that leverages language features
  • Documentation: Use docstrings with proper formatting (Google or NumPy style)

Modern Python Features

Type Hints (Python 3.10+)

from typing import Optional, Union, TypeVar, Generic

def greet(name: str) -> str:
    return f"Hello, {name}!"

def process(data: list[dict[str, Any]]) -> dict[str, int]:
    ...

### Use | for union types (Python 3.10+)
def parse(value: str | int | None) -> str:
    ...

Pattern Matching (Python 3.10+)

match command:
    case ["quit"]:
        return "Goodbye!"
    case ["load", filename]:
        return load_file(filename)
    case ["save", filename, *options]:
        return save_file(filename, options)
    case _:
        return "Unknown command"

Data Classes

from dataclasses import dataclass, field
from datetime import datetime

@dataclass
class User:
    id: int
    name: str
    email: str
    created_at: datetime = field(default_factory=datetime.now)
    roles: list[str] = field(default_factory=list)

Best Practices

Context Managers

from contextlib import contextmanager

@contextmanager
def managed_resource():
    resource = acquire_resource()
    try:
        yield resource
    finally:
        release_resource(resource)

Error Handling

class CustomError(Exception):
    """Custom exception with context."""
    def __init__(self, message: str, code: int):
        self.message = message
        self.code = code
        super().__init__(self.message)

### Use specific exceptions
try:
    result = risky_operation()
except ValueError as e:
    logger.error(f"Invalid value: {e}")
except IOError as e:
    logger.error(f"IO error: {e}")

Async/Await

import asyncio
from typing import AsyncGenerator

async def fetch_data(url: str) -> dict:
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

async def stream_data() -> AsyncGenerator[str, None]:
    for item in data:
        yield item
        await asyncio.sleep(0.1)

Project Structure

project/
├── src/
│   └── package_name/
│       ├── __init__.py
│       ├── core/
│       ├── services/
│       └── utils/
├── tests/
├── pyproject.toml
└── README.md

Configuration

Use pyproject.toml for modern Python projects with tools like Poetry or PDM.

[tool.black]
line-length = 88

[tool.ruff]
line-length = 88
select = ["E", "F", "I", "N", "W"]

[tool.mypy]
strict = true

FAQ

Common questions

Discussion

Questions & comments · 0

Sign In Sign in to leave a comment.