Avoid `PYI015` for valid default value without annotation (#4043)

This commit is contained in:
Dhruv Manilawala 2023-04-21 01:15:47 +05:30 committed by GitHub
parent 6e8d561090
commit 7fd44a3e12
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 51 additions and 0 deletions

View File

@ -84,3 +84,10 @@ class Class1:
# We shouldn't emit Y015 for __all__
__all__ = ["Class1"]
# Ignore the following for PYI015
field26 = typing.Sequence[int]
field27 = list[str]
field28 = builtins.str
field29 = str
field30 = str | bytes | None

View File

@ -91,3 +91,10 @@ class Class1:
# We shouldn't emit Y015 for __all__
__all__ = ["Class1"]
# Ignore the following for PYI015
field26 = typing.Sequence[int]
field27 = list[str]
field28 = builtins.str
field29 = str
field30 = str | bytes | None

View File

@ -219,6 +219,40 @@ fn is_valid_default_value_with_annotation(
false
}
/// Returns `true` if an [`Expr`] appears to be a valid PEP 604 union. (e.g. `int | None`)
fn is_valid_pep_604_union(annotation: &Expr) -> bool {
match &annotation.node {
ExprKind::BinOp {
left,
op: Operator::BitOr,
right,
} => is_valid_pep_604_union(left) && is_valid_pep_604_union(right),
ExprKind::Name { .. }
| ExprKind::Subscript { .. }
| ExprKind::Attribute { .. }
| ExprKind::Constant {
value: Constant::None,
..
} => true,
_ => false,
}
}
/// Returns `true` if an [`Expr`] appears to be a valid default value without an annotation.
fn is_valid_default_value_without_annotation(default: &Expr) -> bool {
matches!(
&default.node,
ExprKind::Call { .. }
| ExprKind::Name { .. }
| ExprKind::Attribute { .. }
| ExprKind::Subscript { .. }
| ExprKind::Constant {
value: Constant::Ellipsis | Constant::None,
..
}
) || is_valid_pep_604_union(default)
}
/// Returns `true` if an [`Expr`] appears to be `TypeVar`, `TypeVarTuple`, `NewType`, or `ParamSpec`
/// call.
fn is_type_var_like_call(context: &Context, expr: &Expr) -> bool {
@ -372,6 +406,9 @@ pub fn assignment_default_in_stub(checker: &mut Checker, targets: &[Expr], value
if is_type_var_like_call(&checker.ctx, value) {
return;
}
if is_valid_default_value_without_annotation(value) {
return;
}
if is_valid_default_value_with_annotation(value, checker, true) {
return;
}