Files
ruff/crates/red_knot_python_semantic/resources/mdtest/annotations/never.md
David Peter 6b9f3d7d7c [red-knot] Import LiteralString/Never from typing_extensions (#14817)
## Summary

`typing.Never` and `typing.LiteralString` are only conditionally
exported from `typing` for Python versions 3.11 and later. We run the
Markdown tests with the default Python version of 3.9, so here we change
the import to `typing_extensions` instead, and add a new test to make
sure we'll continue to understand the `typing`-version of these symbols
for newer versions.

This didn't cause problems so far, as we don't understand
`sys.version_info` branches yet.

## Test Plan

New Markdown tests to make sure this will continue to work in the
future.
2024-12-06 13:57:51 +01:00

1.2 KiB

NoReturn & Never

NoReturn is used to annotate the return type for functions that never return. Never is the bottom type, representing the empty set of Python objects. These two annotations can be used interchangeably.

Function Return Type Annotation

from typing import NoReturn

def stop() -> NoReturn:
    raise RuntimeError("no way")

# revealed: Never
reveal_type(stop())

Assignment

from typing_extensions import NoReturn, Never, Any

# error: [invalid-type-parameter] "Type `typing.Never` expected no type parameter"
x: Never[int]
a1: NoReturn
a2: Never
b1: Any
b2: int

def f():
    # revealed: Never
    reveal_type(a1)
    # revealed: Never
    reveal_type(a2)

    # Never is assignable to all types.
    v1: int = a1
    v2: str = a1
    # Other types are not assignable to Never except for Never (and Any).
    v3: Never = b1
    v4: Never = a2
    v5: Any = b2
    # error: [invalid-assignment] "Object of type `Literal[1]` is not assignable to `Never`"
    v6: Never = 1

typing.Never

typing.Never is only available in Python 3.11 and later:

[environment]
target-version = "3.11"
from typing import Never

x: Never

def f():
    reveal_type(x)  # revealed: Never