mirror of
https://github.com/astral-sh/ruff.git
synced 2026-12-04 02:03:58 +08:00
Skip implicit-return reachability checks for literal None annotations
This commit is contained in:
@@ -299,6 +299,24 @@ def f(cond: bool) -> int:
|
||||
return 2
|
||||
```
|
||||
|
||||
With a literal `None` annotation, ty permits an implicit return and still checks the body, explicit
|
||||
returns, and generator annotations.
|
||||
|
||||
```py
|
||||
def ordinary(flag: bool) -> None:
|
||||
if flag:
|
||||
return 1 # error: [invalid-explicit-return]
|
||||
|
||||
def implicit() -> None:
|
||||
x: str = 1 # error: [invalid-assignment]
|
||||
|
||||
def generator() -> None: # error: [invalid-generator-return-type]
|
||||
yield
|
||||
|
||||
async def async_generator() -> None: # error: [invalid-generator-return-type]
|
||||
yield
|
||||
```
|
||||
|
||||
## Invalid return type
|
||||
|
||||
<!-- snapshot-diagnostics -->
|
||||
|
||||
@@ -199,6 +199,16 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
|
||||
self.infer_scope_body(&function.body);
|
||||
|
||||
if let Some(returns) = function.returns.as_deref() {
|
||||
// An implicit return already satisfies a literal None annotation, regardless
|
||||
// of whether control flow reaches the end of the function.
|
||||
let accepts_implicit_return = returns.is_none_literal_expr();
|
||||
if accepts_implicit_return
|
||||
&& self.return_types_and_ranges.is_empty()
|
||||
&& !scope.is_generator_function(self.index)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let has_empty_body = self.return_types_and_ranges.is_empty()
|
||||
&& function_body_kind(db, env, function, |expr| self.expression_type(expr))
|
||||
== FunctionBodyKind::Stub;
|
||||
@@ -374,7 +384,8 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
|
||||
}
|
||||
}
|
||||
|
||||
if is_end_of_scope_reachable(db, self.scope())
|
||||
if !accepts_implicit_return
|
||||
&& is_end_of_scope_reachable(db, self.scope())
|
||||
&& !Type::none(db, env).is_assignable_to(db, env, *public)
|
||||
{
|
||||
let no_return = self.return_types_and_ranges.is_empty();
|
||||
|
||||
Reference in New Issue
Block a user