Skip to main content

Django typing helper

Project description

django-autotyping

Automatically add type hints for Django powered applications.

To understand the purpose of this library, you can refer to this article.

django-autotyping is built with LibCST.

Python versions PyPI version Ruff

[!WARNING]
This project is still work in progress.

Installation

Through pip:

pip install django-autotyping

Usage

django-autotyping is usable in two ways:

  • As a Django development application.
  • As a linter that will automatically apply changes to your code.

Django application - dynamic stub files

django-autotyping can generate custom dynamic stubs for your application:

  • Add django_autotyping to your INSTALLED_APPS.
  • In your configuration, set AUTOTYPING_STUBS_DIR to a directory where local stubs should live. By default, pyright looks for the directory typings/. For mypy, you will have to configure the mypy_path value (or use the MYPY_PATH environment variable).
  • Optionally, you can disable specific rules by setting AUTOTYPING_DISABLED_RULES.
  • Install django-stubs into your environment.

Stubs will be generated when the post_migrate signal is emitted (you can still run the migrate command even if no migrations are to be applied).

Available rules

Add type hints to related fields (DJAS001)

A codemod that will add overloads to the __init__ methods of related fields.

This codemod is meant to be applied on the django-stubs/db/models/fields/related.pyi stub file.

class ForeignKey(ForeignObject[_ST, _GT]):
    # For each model, will add two overloads:
    # - 1st: `null: Literal[True]`, which will parametrize `ForeignKey` get types as `Optional`.
    # - 2nd: `null: Literal[False] = ...` (the default).
    # `to` is annotated as a `Literal`, with two values: {app_label}.{model_name} and {model_name}.
    # If two models from different apps have the same name, only the first form will be available.
    @overload
    def __init__(
        self: ForeignKey[MyModel | None, MyModel | None],
        to: Literal["MyModel", "myapp.MyModel"],
        ...
    ) -> None: ...

Add type hints to Manager and QuerySet methods (DJAS002)

[!WARNING]
This rule is still in progress, and waiting on some Python typing features to land.

Linter - automatic codemods

django-autotyping can be also used as a CLI program. Running the CLI will apply explicit annotations to your code.

usage: Add type hints to your models for better auto-completion.

positional arguments:
  path                  Path to the directory containing the Django application. This directory should contain your `manage.py` file.

options:
  -h, --help            show this help message and exit
  --settings-module SETTINGS_MODULE
                        Value of the `DJANGO_SETTINGS_MODULE` environment variable (a dotted Python path).
  --diff                Show diff instead of applying changes to existing files.
  --disable [{DJA001} ...]
                        Rules to be disabled.
  --type-checking-block
                        Whether newly added imports should be in an `if TYPE_CHECKING` block (avoids circular imports).
  --assume-class-getitem
                        Whether generic classes in stubs files but not at runtime should be assumed to have a `__class_getitem__` method. This can be
                        achieved by using `django-stubs-ext` or manually.

Rules

Add type hints to forward relations (DJA001)

All subclasses of RelatedField will be taken into account.

from typing import TYPE_CHECKING

from django.db import models

# Model is imported in an `if TYPE_CHECKING` block if `--type-checking-block` is used.
if TYPE_CHECKING:
    # Related model is imported from the corresponding apps models module:
    from myproject.reporters.models import Reporter


class Article(models.Model):
    # If the field supports `__class_getitem__` at runtime, it is parametrized directly:
    reporter = models.ForeignKey["Reporter"](
        "reporters.Reporter",
        on_delete=models.CASCADE,
    )

    # Otherwise, an explicit annotation is used. No unnecessary import if model is in the same file.
    article_version: "models.OneToOneField[ArticleVersion]" = models.OneToOneField(
        "ArticleVersion",
        on_delete=models.CASCADE,
    )

[!NOTE]
As of today, generated type hints will only play well with django-types. django-stubs requires a type for both the __set__ and __get__ types. Instead, it is recommended to use the corresponding dynamic stub rule (DJAS001).

Add type hints for reverse relationships (DJA002)

[!WARNING]
This rule is still in progress.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django-autotyping-0.1.0.tar.gz (21.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_autotyping-0.1.0-py3-none-any.whl (26.9 kB view details)

Uploaded Python 3

File details

Details for the file django-autotyping-0.1.0.tar.gz.

File metadata

  • Download URL: django-autotyping-0.1.0.tar.gz
  • Upload date:
  • Size: 21.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.10.13

File hashes

Hashes for django-autotyping-0.1.0.tar.gz
Algorithm Hash digest
SHA256 8b2e45dc134112c25d28c6562327388ca44704663def5ecc4725c01c8e140b64
MD5 425e0df93d9d5a55591516ea01074d38
BLAKE2b-256 28a6dd842c9d6042bfc8d46e4d25d3d61b93de8ee22f05ffbf95eceab915530e

See more details on using hashes here.

File details

Details for the file django_autotyping-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for django_autotyping-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 e0b36f113da531ff1a87c63ecad1aa6a9985976ebcb15839b58f67aea81c1959
MD5 f0a8594ed15be47479668e6490d8ab86
BLAKE2b-256 1219c7f6830fb54b4aad7c345d4fd8732b043baffa40eb6241e9062dffac36c7

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page