Skip to content

[Enhancement] Improve Developer Experience (DX) by using TypedDict and Unpack (PEP 692) for Field.__init__ #2168

@ropmyung

Description

@ropmyung

🚀 Summary

As a developer using TortoiseORM with VS Code (Pylance/Pyright), I've noticed that defining models can be a bit "blind" because Field classes use **kwargs: Any in their __init__.

I would like to propose using PEP 692 (Unpack with TypedDict) to provide explicit type hints for field arguments. This would significantly improve the autocompletion and static analysis experience for all users.

😟 Current Problem

Currently, most Field classes (e.g., IntField, CharField) have an __init__ signature like this:

def __init__(self, **kwargs: Any) -> None: ...

Because of Any, IDEs cannot suggest valid arguments like pk, null, default, or index. Developers have to refer to the documentation constantly, and simple typos in argument names are not caught by type checkers (Mypy/Pyright) in "Standard" or "Strict" modes.

💡 Proposed Solution

By leveraging PEP 692, we can define a TypedDict for common field arguments. This allows the IDE to provide real-time suggestions while maintaining the flexibility of **kwargs.

Example Implementation:

from typing import TypedDict, Optional, Any
from typing_extensions import Unpack  # For compatibility with older Python versions

class FieldArgs(TypedDict, total=False):
    pk: bool
    null: bool
    default: Any
    index: bool
    unique: bool
    db_index: bool
    description: Optional[str]
    source_field: Optional[str]
    generated: bool
    # etc.

class Field:
    def __init__(self, **kwargs: Unpack[FieldArgs]) -> None:
        ...

🎯 Benefits

  1. Full Autocompletion: IDEs like VS Code (Pylance) will show the list of valid arguments as soon as the user types (.
  2. Early Bug Detection: Type checkers will flag invalid arguments or incorrect types (e.g., passing a string to null).
  3. Self-Documenting Code: The code itself becomes the documentation for what a Field can accept.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions