microsoft / pyright

Static Type Checker for Python
Other
13.15k stars 1.4k forks source link

Pyright Flags Unreachable yield, but Python Treats Function as a Generator #8920

Closed Raguggg closed 1 week ago

Raguggg commented 1 week ago

Bug Report: Unreachable yield but Function Treated as a Generator

Describe the bug Pyright is flagging unreachable code correctly when a yield statement is placed after a return, but Python still considers the function a generator. This creates a mismatch between Pyright's static analysis and Python's runtime behavior.

Steps to reproduce:

def test():
    return
    yield  # Code is unreachable

print(test())

Expected behavior Pyright flags the unreachable code (which is correct), but since Python treats this function as a generator due to the yield keyword, it might lead to a discrepancy in behavior between the type checker and Python's runtime. image

Version: 1.1.375 image

erictraut commented 1 week ago

Pyright is working as intended here, so I don't consider this a bug.

The yield statement is unreachable, so pyright is correct to report it as such. This isn't reported as an error but rather as a "tagged hint", telling the editor that it should display the code with a subtle grayed-out appearance. Here's what it looks like in VS Code, for example:

image

It looks like your editor is displaying the tagged hint like a regular diagnostic. You therefore may want to disable all tagged hints. You can do so by setting the LSP setting pyright.disableTaggedHints to true.

Pyright does understand that the Python runtime treats this function as a generator. If you hover over the function name, you'll see that the inferred return type is Generator[Never, Any, None].