Skip to content

Assert at end of if statement does not help mypy value inference #3431

Closed as not planned
@chrish42

Description

@chrish42

While working on making zulip pass with mypy --strict-optional, I ran into the following piece of code. Mypy was essentially saying that message.get_realm() was not guaranteed to work ("Not all parts of the union have get_realm() method", or somesuch.)

if message is None:
    message = Message.objects.select_related().get(id=message_id)

rendered_content = render_markdown(message, content, realm=message.get_realm())

Let's assume, at least for here, that the get() call will never return None. I tried the following change, but mypy was still giving the exact same error:

if message is None:
    message = Message.objects.select_related().get(id=message_id)
    assert message is not None # ADDED

rendered_content = render_markdown(message, content, realm=message.get_realm())

However, with this change, mypy was now happy with the code snippet:

if message is None:
    message = Message.objects.select_related().get(id=message_id)

assert message is not None # ADDED, but outside the if, now.
rendered_content = render_markdown(message, content, realm=message.get_realm())

The two asserts clearly have the same code behavior of making it impossible for message to be None when we reach the rendered_content = ... line, but mypy only understands that currently (version 5.111) for the last code snippet only. Opening this bug report for discussion of that.

(Feel free to change the title of this bug report to a more meaningful / better one.)

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions