Skip to content

Mypy flags unreachable on pre-save and checking for instance ID #2014

Open
@sshishov

Description

@sshishov

Bug report

We are implementing pre-save of some models and there usually we check if the instance is being created or not by doing

if instance.id is None:
    ...  # creating the instance logic

What's wrong

import typing as t

from django.db import models as django_models
from django import dispatch as django_dispatch

@django_dispatch.receiver(django_models.signals.pre_save, sender=my_app.MyModel)
def project_pre_save(sender: type[my_app.MyModel], instance: my_app.MyModel, **kwargs: t.Any) -> None:
    if instance.id is None:
        add_something_to_instance(instance)  # <-- Statement is unreachable  [unreachable]
    ...

In this case mypy flagging this with the following error indicated above

How is that should be

On pre-save instance.id should be either the Field or None as it can be None in case of creation of the object.
Do not know how to properly implement it though...

System information

  • OS: MacOS / Linux
  • python version: 3.11.5
  • django version: 3.2.23
  • mypy version: 1.9.0
  • django-stubs version: 4.2.7
  • django-stubs-ext version: 4.2.7

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions