Skip to content

Comments

Add explanations of the yield statement to common_issues.rst Fixes #17996#18422

Open
keainye wants to merge 1 commit intopython:masterfrom
keainye:master
Open

Add explanations of the yield statement to common_issues.rst Fixes #17996#18422
keainye wants to merge 1 commit intopython:masterfrom
keainye:master

Conversation

@keainye
Copy link

@keainye keainye commented Jan 6, 2025

Fixes #17996 @JelleZijlstra @hauntsaninja @tilboerner Please review :)

Add explanations of the yield statement to common_issues.rst.

No need for a test. Just modified the doc.

def gen() -> Generator[int]:
... # error: Missing return statement

This kind of mistake is common in unfinished functions (the function body is ``...``).
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add a sentence about overload here? overload bodies need to contain yield as well (see rejected #17435) . This would also close #17430 then.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, I'll add.

Therefore, when using ``mypy`` to check types, we need to declare the return types
of such functions as Generator (or AsyncGenerator when the function is async).

A common mistake is that we declared the return type of a function as
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And this is wrong: "Missing return statement" is not specific to Generator, that's just because the return type is non-None and the body s trivial.

A reasonable function can return a Generator or Iterator and contain no yield (this passes):

from collections.abc import Generator

def fn() -> Generator[int]:
    return (i for i in range(5))

On the other hand, missing return statement causes a diagnostic without Generator too (except for stub files):

def fn() -> int:
    ...  # E: Missing return statement  [empty-body]

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That sounds reasonable, I'll re-write these lines.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Cannot set return type of asynccontextmanagers in Protocol classes

3 participants