Comprehensive type stubs for Django framework enabling static type checking with mypy
—
Django-stubs includes a comprehensive MyPy plugin that enhances type checking for Django-specific patterns, providing better inference for QuerySets, model fields, forms, and request handling.
Main plugin class and configuration for enhanced Django type checking.
class DjangoPlugin:
"""
Main MyPy plugin class for Django type checking enhancement.
Provides Django-specific type inference and validation.
"""
def __init__(self, options: Options): ...
def get_method_context_hook(self, fullname: str): ...
def get_method_signature_hook(self, fullname: str): ...
def get_attribute_hook(self, fullname: str): ...
def get_class_decorator_hook(self, fullname: str): ...
def get_metaclass_hook(self, fullname: str): ...
def get_base_class_hook(self, fullname: str): ...
def get_customize_class_mro_hook(self, fullname: str): ...
def get_dynamic_class_hook(self, fullname: str): ...
class DjangoPluginConfig:
"""
Configuration settings for Django MyPy plugin.
Controls plugin behavior and feature flags.
"""
django_settings_module: str = None
ignore_missing_model_attributes: bool = False
ignore_missing_settings: bool = False
strict_settings: bool = False
def __init__(self, config_file: str = None): ...Enhanced type inference for Django model fields and attributes.
class ModelFieldTransformer:
"""
Transformer for model field type resolution.
Provides accurate type information for model fields and relationships.
"""
def transform_model_field(self, field_node, field_type: Type, ctx) -> Type: ...
def get_field_descriptor_type(self, field: Field, is_set: bool = False) -> Type: ...
def resolve_field_access_type(self, field: Field, access_type: str) -> Type: ...
# Field type mappings
def get_char_field_type(self, max_length: int = None) -> Type: ...
def get_integer_field_type(self) -> Type: ...
def get_boolean_field_type(self) -> Type: ...
def get_datetime_field_type(self) -> Type: ...
def get_foreign_key_type(self, related_model: Type) -> Type: ...
def get_many_to_many_type(self, related_model: Type) -> Type: ...
class FieldDescriptorTypes:
"""
Type definitions for model field descriptors.
Provides proper typing for field access patterns.
"""
# Descriptor return types
FIELD_GET_TYPES: dict = {
'CharField': 'str',
'TextField': 'str',
'IntegerField': 'int',
'BooleanField': 'bool',
'DateTimeField': 'datetime.datetime',
'DateField': 'datetime.date',
'TimeField': 'datetime.time',
'DecimalField': 'decimal.Decimal',
'FloatField': 'float',
'EmailField': 'str',
'URLField': 'str',
'UUIDField': 'uuid.UUID',
'JSONField': 'Any',
}
# Descriptor set types (for assignment)
FIELD_SET_TYPES: dict = {
'CharField': 'Union[str, Combinable]',
'TextField': 'Union[str, Combinable]',
'IntegerField': 'Union[int, Combinable]',
'BooleanField': 'Union[bool, Combinable]',
'DateTimeField': 'Union[datetime.datetime, str, Combinable]',
'DateField': 'Union[datetime.date, str, Combinable]',
'TimeField': 'Union[datetime.time, str, Combinable]',
'DecimalField': 'Union[Decimal, int, float, str, Combinable]',
'FloatField': 'Union[float, int, Combinable]',
}Enhanced type checking for QuerySet operations and method chaining.
class QuerySetMethodResolver:
"""
Resolver for QuerySet method types and return values.
Provides accurate type inference for QuerySet operations.
"""
def resolve_queryset_method(self, method_name: str, base_type: Type, args: list) -> Type: ...
def get_queryset_filter_type(self, base_type: Type, filter_args: dict) -> Type: ...
def get_values_return_type(self, base_type: Type, field_names: list) -> Type: ...
def get_values_list_return_type(self, base_type: Type, field_names: list, flat: bool = False, named: bool = False) -> Type: ...
def get_annotate_return_type(self, base_type: Type, annotations: dict) -> Type: ...
def get_aggregate_return_type(self, aggregations: dict) -> Type: ...
# QuerySet method return types
QUERYSET_METHOD_TYPES: dict = {
'all': lambda base_type: f'QuerySet[{base_type}, {base_type}]',
'filter': lambda base_type: f'QuerySet[{base_type}, {base_type}]',
'exclude': lambda base_type: f'QuerySet[{base_type}, {base_type}]',
'order_by': lambda base_type: f'QuerySet[{base_type}, {base_type}]',
'distinct': lambda base_type: f'QuerySet[{base_type}, {base_type}]',
'select_related': lambda base_type: f'QuerySet[{base_type}, {base_type}]',
'prefetch_related': lambda base_type: f'QuerySet[{base_type}, {base_type}]',
'get': lambda base_type: base_type,
'first': lambda base_type: f'Optional[{base_type}]',
'last': lambda base_type: f'Optional[{base_type}]',
'exists': lambda base_type: 'bool',
'count': lambda base_type: 'int',
'delete': lambda base_type: 'Tuple[int, Dict[str, int]]',
'update': lambda base_type: 'int',
}
class ValuesQuerySetResolver:
"""
Special resolver for ValuesQuerySet type inference.
Handles values() and values_list() return type resolution.
"""
def resolve_values_type(self, model_type: Type, field_names: list) -> Type: ...
def resolve_values_list_type(self, model_type: Type, field_names: list, flat: bool = False, named: bool = False) -> Type: ...
def get_field_value_type(self, model_type: Type, field_name: str) -> Type: ...
# Generate proper TypedDict for values() calls
def create_values_typed_dict(self, model_type: Type, field_names: list) -> Type: ...Type inference enhancement for model managers and custom manager methods.
class ManagerClassProcessor:
"""
Processor for Manager class creation and method resolution.
Provides proper typing for custom manager methods.
"""
def process_manager_class(self, manager_class: Type, model_type: Type) -> Type: ...
def add_manager_methods(self, manager_class: Type, model_type: Type) -> None: ...
def resolve_manager_method_type(self, method_name: str, manager_class: Type, model_type: Type) -> Type: ...
# Default manager method types
MANAGER_METHOD_TYPES: dict = {
'get_queryset': lambda model_type: f'QuerySet[{model_type}, {model_type}]',
'all': lambda model_type: f'QuerySet[{model_type}, {model_type}]',
'filter': lambda model_type: f'QuerySet[{model_type}, {model_type}]',
'exclude': lambda model_type: f'QuerySet[{model_type}, {model_type}]',
'get': lambda model_type: model_type,
'create': lambda model_type: model_type,
'get_or_create': lambda model_type: f'Tuple[{model_type}, bool]',
'update_or_create': lambda model_type: f'Tuple[{model_type}, bool]',
'bulk_create': lambda model_type: f'List[{model_type}]',
'bulk_update': lambda model_type: 'int',
}
class RelatedManagerProcessor:
"""
Processor for related object managers (ForeignKey, ManyToMany).
Provides typing for relationship manager methods.
"""
def process_related_manager(self, field: Field, related_type: Type) -> Type: ...
def get_foreign_key_manager_type(self, related_type: Type) -> Type: ...
def get_many_to_many_manager_type(self, related_type: Type) -> Type: ...
def get_reverse_foreign_key_manager_type(self, related_type: Type) -> Type: ...Enhanced type checking for Django forms and form fields.
class FormFieldProcessor:
"""
Processor for form field types and validation.
Provides accurate typing for form field operations.
"""
def process_form_field(self, field_type: Type, field_kwargs: dict) -> Type: ...
def get_field_clean_return_type(self, field_type: Type) -> Type: ...
def get_widget_type(self, field_type: Type, widget_class: Type = None) -> Type: ...
# Form field clean method return types
FIELD_CLEAN_TYPES: dict = {
'CharField': 'str',
'IntegerField': 'int',
'BooleanField': 'bool',
'EmailField': 'str',
'URLField': 'str',
'DateField': 'datetime.date',
'DateTimeField': 'datetime.datetime',
'TimeField': 'datetime.time',
'DecimalField': 'decimal.Decimal',
'FloatField': 'float',
'ChoiceField': 'str',
'MultipleChoiceField': 'List[str]',
'FileField': 'UploadedFile',
'ImageField': 'UploadedFile',
'ModelChoiceField': 'Model',
'ModelMultipleChoiceField': 'QuerySet',
}
class ModelFormProcessor:
"""
Processor for ModelForm type inference and validation.
Connects model fields to form fields with proper typing.
"""
def process_model_form(self, form_class: Type, model_class: Type) -> Type: ...
def get_model_form_fields(self, model_class: Type, fields: list = None, exclude: list = None) -> dict: ...
def convert_model_field_to_form_field(self, model_field: Field) -> Type: ...
def get_form_save_type(self, model_class: Type, commit: bool = True) -> Type: ...
class FormSetProcessor:
"""
Processor for FormSet and ModelFormSet types.
Provides typing for formset operations and validation.
"""
def process_formset(self, form_class: Type, formset_class: Type) -> Type: ...
def process_model_formset(self, model_class: Type, form_class: Type) -> Type: ...
def get_formset_forms_type(self, form_class: Type) -> Type: ...
def get_formset_save_type(self, model_class: Type) -> Type: ...Enhanced type inference for HttpRequest and user attributes.
class RequestTypeResolver:
"""
Resolver for HttpRequest type inference and user types.
Provides accurate typing for request attributes and methods.
"""
def resolve_request_type(self, request_type: Type) -> Type: ...
def get_request_user_type(self, request_type: Type) -> Type: ...
def get_request_session_type(self) -> Type: ...
def resolve_request_method_type(self, method_name: str) -> Type: ...
# Request attribute types
REQUEST_ATTRIBUTE_TYPES: dict = {
'method': 'str',
'path': 'str',
'path_info': 'str',
'GET': 'QueryDict',
'POST': 'QueryDict',
'COOKIES': 'Dict[str, str]',
'FILES': 'MultiValueDict',
'META': 'Dict[str, str]',
'content_type': 'str',
'content_params': 'Dict[str, str]',
'resolver_match': 'ResolverMatch',
}
class UserTypeResolver:
"""
Resolver for User model types in requests and authentication.
Handles custom user models and AnonymousUser types.
"""
def resolve_user_type(self, user_model: Type = None) -> Type: ...
def get_authenticated_user_type(self) -> Type: ...
def get_anonymous_user_type(self) -> Type: ...
def resolve_user_attribute_type(self, attr_name: str, user_type: Type) -> Type: ...Type checking for Django settings access and configuration.
class SettingsTypeResolver:
"""
Resolver for Django settings attribute types.
Provides type information for settings access patterns.
"""
def resolve_settings_attribute(self, attr_name: str) -> Type: ...
def get_settings_type_from_default(self, setting_name: str, default_value) -> Type: ...
def validate_settings_access(self, attr_name: str) -> bool: ...
# Common Django settings types
SETTINGS_TYPES: dict = {
'DEBUG': 'bool',
'SECRET_KEY': 'str',
'ALLOWED_HOSTS': 'List[str]',
'INSTALLED_APPS': 'List[str]',
'MIDDLEWARE': 'List[str]',
'ROOT_URLCONF': 'str',
'TEMPLATES': 'List[Dict[str, Any]]',
'DATABASES': 'Dict[str, Dict[str, Any]]',
'STATIC_URL': 'str',
'STATIC_ROOT': 'str',
'MEDIA_URL': 'str',
'MEDIA_ROOT': 'str',
'DEFAULT_AUTO_FIELD': 'str',
'USE_TZ': 'bool',
'USE_I18N': 'bool',
'TIME_ZONE': 'str',
'LANGUAGE_CODE': 'str',
}
class LazySettingsProcessor:
"""
Processor for lazy settings object type resolution.
Handles django.conf.settings lazy loading patterns.
"""
def process_lazy_settings(self) -> Type: ...
def resolve_lazy_attribute_access(self, attr_name: str) -> Type: ...
def validate_settings_configured(self) -> bool: ...Enhanced type checking for ORM field lookups and query expressions.
class ORMLookupProcessor:
"""
Processor for ORM lookup type validation and inference.
Validates field lookups in filter/exclude/get operations.
"""
def process_lookup_expression(self, field_name: str, lookup_type: str, model_type: Type) -> Type: ...
def validate_field_lookup(self, field: Field, lookup_type: str) -> bool: ...
def get_lookup_value_type(self, field: Field, lookup_type: str) -> Type: ...
# Field lookup compatibility matrix
FIELD_LOOKUP_TYPES: dict = {
'CharField': ['exact', 'iexact', 'contains', 'icontains', 'startswith', 'istartswith',
'endswith', 'iendswith', 'regex', 'iregex', 'in', 'isnull'],
'IntegerField': ['exact', 'lt', 'lte', 'gt', 'gte', 'in', 'range', 'isnull'],
'DateTimeField': ['exact', 'lt', 'lte', 'gt', 'gte', 'in', 'range', 'year', 'month',
'day', 'hour', 'minute', 'second', 'date', 'time', 'isnull'],
'BooleanField': ['exact', 'isnull'],
'ForeignKey': ['exact', 'in', 'isnull', 'pk', 'related_field_lookups'],
}
class QueryExpressionProcessor:
"""
Processor for query expression types (F, Q, etc.).
Provides typing for complex query expressions and aggregations.
"""
def process_f_expression(self, field_name: str, model_type: Type) -> Type: ...
def process_q_expression(self, q_expr: dict, model_type: Type) -> Type: ...
def process_case_expression(self, when_clauses: list, default_value: Type) -> Type: ...
def process_subquery_expression(self, subquery_type: Type) -> Type: ...
class AggregationProcessor:
"""
Processor for aggregation function types and return values.
Provides accurate typing for aggregate operations.
"""
def process_aggregation(self, func_name: str, field_type: Type) -> Type: ...
def get_aggregate_return_type(self, func_name: str, field_type: Type) -> Type: ...
# Aggregation function return types
AGGREGATION_TYPES: dict = {
'Count': 'int',
'Sum': lambda field_type: field_type,
'Avg': lambda field_type: 'Optional[Decimal]' if field_type == 'Decimal' else 'Optional[float]',
'Min': lambda field_type: f'Optional[{field_type}]',
'Max': lambda field_type: f'Optional[{field_type}]',
'StdDev': 'Optional[float]',
'Variance': 'Optional[float]',
}Custom error codes for Django-specific type checking issues.
class DjangoErrorCodes:
"""
Error codes for Django-specific MyPy errors.
Provides descriptive error messages for Django patterns.
"""
# Model-related errors
INVALID_FIELD_ACCESS: str = 'django-field-access'
MISSING_MODEL_ATTRIBUTE: str = 'django-missing-model-attr'
INVALID_MANAGER_METHOD: str = 'django-manager-method'
# QuerySet-related errors
INVALID_QUERYSET_METHOD: str = 'django-queryset-method'
INVALID_LOOKUP: str = 'django-invalid-lookup'
INCOMPATIBLE_LOOKUP_TYPE: str = 'django-lookup-type'
# Form-related errors
INVALID_FORM_FIELD: str = 'django-form-field'
MISSING_FORM_ATTRIBUTE: str = 'django-missing-form-attr'
# Settings-related errors
MISSING_SETTING: str = 'django-missing-setting'
INVALID_SETTING_TYPE: str = 'django-setting-type'
# Request-related errors
INVALID_REQUEST_ATTRIBUTE: str = 'django-request-attr'
MISSING_USER_ATTRIBUTE: str = 'django-user-attr'
def register_error_code(code: str, description: str, category: str = 'django') -> None:
"""
Register custom Django error code with MyPy.
Args:
code: Error code identifier
description: Human-readable error description
category: Error category for grouping
"""
def emit_django_error(ctx, code: str, message: str, node) -> None:
"""
Emit Django-specific error through MyPy.
Args:
ctx: MyPy context object
code: Django error code
message: Error message
node: AST node where error occurred
"""Integration points for extending MyPy's Django type checking.
class DjangoMethodSignatureHook:
"""
Hook for customizing method signature inference.
Allows custom typing for Django method patterns.
"""
def __call__(self, ctx) -> CallableType: ...
class DjangoAttributeHook:
"""
Hook for customizing attribute type inference.
Provides custom typing for Django attribute access.
"""
def __call__(self, ctx) -> Type: ...
class DjangoClassDecoratorHook:
"""
Hook for processing Django class decorators.
Handles typing for Django decorator patterns.
"""
def __call__(self, ctx) -> None: ...
class DjangoMetaclassHook:
"""
Hook for processing Django metaclasses.
Handles Model metaclass and other Django metaclass patterns.
"""
def __call__(self, ctx) -> None: ...
def register_django_hook(hook_name: str, hook_function) -> None:
"""
Register custom Django plugin hook.
Args:
hook_name: Name of the hook to register
hook_function: Hook implementation function
"""
def get_django_hook(hook_name: str):
"""
Get registered Django plugin hook by name.
Args:
hook_name: Name of hook to retrieve
Returns:
Hook function or None if not registered
"""Utility functions for Django plugin development and debugging.
def is_django_model(cls: Type) -> bool:
"""
Check if class is a Django model.
Args:
cls: Class type to check
Returns:
True if class inherits from django.db.models.Model
"""
def is_django_form(cls: Type) -> bool:
"""
Check if class is a Django form.
Args:
cls: Class type to check
Returns:
True if class inherits from django.forms.Form
"""
def is_django_manager(cls: Type) -> bool:
"""
Check if class is a Django manager.
Args:
cls: Class type to check
Returns:
True if class inherits from django.db.models.Manager
"""
def get_model_from_manager(manager_type: Type) -> Type:
"""
Extract model type from manager class.
Args:
manager_type: Manager class type
Returns:
Associated model type
"""
def resolve_lazy_reference(reference: str, module_name: str) -> Type:
"""
Resolve lazy string reference to actual type.
Args:
reference: String reference to resolve
module_name: Module context for resolution
Returns:
Resolved type object
"""
def debug_django_plugin(message: str, level: str = 'info') -> None:
"""
Debug logging for Django plugin development.
Args:
message: Debug message to log
level: Log level (debug, info, warning, error)
"""Install with Tessl CLI
npx tessl i tessl/pypi-django-stubs