Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[flake8-pyi] Fix PYI049 false negatives on call-based TypedDicts #9567

Merged
merged 2 commits into from
Jan 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,8 @@ class _UsedTypedDict(TypedDict):

class _CustomClass(_UsedTypedDict):
bar: list[int]

_UnusedTypedDict3 = TypedDict("_UnusedTypedDict3", {"foo": int})
_UsedTypedDict3 = TypedDict("_UsedTypedDict3", {"bar": bytes})

def uses_UsedTypedDict3(arg: _UsedTypedDict3) -> None: ...
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,8 @@ else:

class _CustomClass2(_UsedTypedDict2):
bar: list[int]

_UnusedTypedDict3 = TypedDict("_UnusedTypedDict3", {"foo": int})
_UsedTypedDict3 = TypedDict("_UsedTypedDict3", {"bar": bytes})

def uses_UsedTypedDict3(arg: _UsedTypedDict3) -> None: ...
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::map_subscript;
use ruff_python_ast::{self as ast, Expr, Stmt};
use ruff_python_semantic::Scope;
use ruff_python_semantic::{Scope, SemanticModel};
use ruff_text_size::Ranged;

use crate::checkers::ast::Checker;
Expand Down Expand Up @@ -313,11 +313,16 @@ pub(crate) fn unused_private_typed_dict(
scope: &Scope,
diagnostics: &mut Vec<Diagnostic>,
) {
let semantic = checker.semantic();

for binding in scope
.binding_ids()
.map(|binding_id| checker.semantic().binding(binding_id))
.map(|binding_id| semantic.binding(binding_id))
{
if !(binding.kind.is_class_definition() && binding.is_private_declaration()) {
if !binding.is_private_declaration() {
continue;
}
if !(binding.kind.is_class_definition() || binding.kind.is_assignment()) {
continue;
}
if binding.is_used() {
Expand All @@ -327,23 +332,64 @@ pub(crate) fn unused_private_typed_dict(
let Some(source) = binding.source else {
continue;
};
let Stmt::ClassDef(class_def) = checker.semantic().statement(source) else {
continue;
};

if !class_def
.bases()
.iter()
.any(|base| checker.semantic().match_typing_expr(base, "TypedDict"))
{
let Some(class_name) = extract_typeddict_name(semantic.statement(source), semantic) else {
continue;
}
};

diagnostics.push(Diagnostic::new(
UnusedPrivateTypedDict {
name: class_def.name.to_string(),
name: class_name.to_string(),
},
binding.range(),
));
}
}

fn extract_typeddict_name<'a>(stmt: &'a Stmt, semantic: &SemanticModel) -> Option<&'a str> {
let is_typeddict = |expr: &ast::Expr| semantic.match_typing_expr(expr, "TypedDict");
match stmt {
// E.g. return `Some("Foo")` for the first one of these classes,
// and `Some("Bar")` for the second:
//
// ```python
// import typing
// from typing import TypedDict
//
// class Foo(TypedDict):
// x: int
//
// T = typing.TypeVar("T")
//
// class Bar(typing.TypedDict, typing.Generic[T]):
// y: T
// ```
Stmt::ClassDef(class_def @ ast::StmtClassDef { name, .. }) => {
AlexWaygood marked this conversation as resolved.
Show resolved Hide resolved
if class_def.bases().iter().any(is_typeddict) {
Some(name)
} else {
None
}
}
// E.g. return `Some("Baz")` for this assignment,
// which is an accepted alternative way of creating a TypedDict type:
//
// ```python
// import typing
// Baz = typing.TypedDict("Baz", {"z": bytes})
// ```
Stmt::Assign(ast::StmtAssign { targets, value, .. }) => {
let [target] = targets.as_slice() else {
return None;
};
let ast::ExprName { id, .. } = target.as_name_expr()?;
let ast::ExprCall { func, .. } = value.as_call_expr()?;
if is_typeddict(func) {
Some(id)
} else {
None
}
}
_ => None,
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,13 @@ PYI049.py:9:7: PYI049 Private TypedDict `_UnusedTypedDict2` is never used
10 | bar: int
|

PYI049.py:20:1: PYI049 Private TypedDict `_UnusedTypedDict3` is never used
|
18 | bar: list[int]
19 |
20 | _UnusedTypedDict3 = TypedDict("_UnusedTypedDict3", {"foo": int})
| ^^^^^^^^^^^^^^^^^ PYI049
21 | _UsedTypedDict3 = TypedDict("_UsedTypedDict3", {"bar": bytes})
|


Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,13 @@ PYI049.pyi:10:7: PYI049 Private TypedDict `_UnusedTypedDict2` is never used
11 | bar: int
|

PYI049.pyi:34:1: PYI049 Private TypedDict `_UnusedTypedDict3` is never used
|
32 | bar: list[int]
33 |
34 | _UnusedTypedDict3 = TypedDict("_UnusedTypedDict3", {"foo": int})
| ^^^^^^^^^^^^^^^^^ PYI049
35 | _UsedTypedDict3 = TypedDict("_UsedTypedDict3", {"bar": bytes})
|