Description
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.)