Skip to content

Dynamic stubs

django-autotyping can generate customized type stubs depending on the current state of your Django project:

python manage.py generate_stubs --local-stubs-dir typings/ --ignore DJAS001

Available rules

The following is a list of the available rules related to dynamic stubs:

Type checker configuration

Before making use of this feature, you must configure your type checker to discover your custom stubs:

Configuration

This section describes the available configuration options for stubs generation. These values must be set as a dictionary under the STUBS_GENERATION key:

AUTOTYPING = {
    "STUBS_GENERATION": {
        "LOCAL_STUBS_DIR": Path(...),
    }
}

Configuration for dynamic stubs generation.

LOCAL_STUBS_DIR: Path | None = None

The directory of the local type stubs. If not set, this setting must be set as a CLI argument.

SOURCE_STUBS_DIR: Path | None = None

The directory of the source django-stubs to be used. Will default to the first entry in site packages.

ALLOW_PLAIN_MODEL_REFERENCES: bool = True

Whether string references in the form of {model_name} should be generated in overloads.

If set to True, both {model_name} and {app_label}.{model_name} are allowed (unless the model name has a duplicate in a different app).

Affected rules: DJAS001.

ALLOW_NONE_SET_TYPE: bool = False

Whether to allow having the __set__ type variable set to None, even if the field is not nullable.

While Django allows setting most model instance fields to any value (before saving), it is generally a bad practice to do so. However, it might be beneficial to allow None to be set temporarly.

This also works for foreign fields, where unlike standard fields, the Django descriptor used only allows model instances and None to be set.

Affected rules: DJAS001.

MODEL_FIELDS_OPTIONAL: bool = True

Whether all model fields should be considered optional when creating model instances.

This affects the following signatures:

A lot can happen behind the scenes when instantiating models. Even if a field doesn't have a default value provided, the database could have triggers implemented that would provide one. This is why, by default, this configuration attribute defaults to True. If set to False, django-autotyping will try its best to determine required fields, namely by checking if:

  • the field can be null or blank
  • the field is a primary key
  • the field has a default or a database default value set
  • the field is a subclass of DateField and has auto_now or auto_now_add set to True.

Affected rules: DJAS002, DJAS003.

ALLOW_REVERSE_ARGS: bool = False

Whether type checking should be added to the args argument of reverse.

By default, this is set to False to avoid having too many overloads being generated. Moreover, only tuples can be type checked, and most people are using lists for this argument. Instead, it is recommended to use the kwargs argument.

Affected rules: DJAS015.