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

Do not fix NamedTuple calls containing both a list of fields and keywords #5799

Merged
merged 7 commits into from
Jul 17, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -93,11 +93,7 @@ fn match_named_tuple_assign<'a>(

/// Generate a `Stmt::AnnAssign` representing the provided property
/// definition.
fn create_property_assignment_stmt(
property: &str,
annotation: &Expr,
value: Option<&Expr>,
) -> Stmt {
fn create_property_assignment_stmt(property: &str, annotation: &Expr) -> Stmt {
ast::StmtAnnAssign {
target: Box::new(
ast::ExprName {
Expand All @@ -108,34 +104,15 @@ fn create_property_assignment_stmt(
.into(),
),
annotation: Box::new(annotation.clone()),
value: value.map(|value| Box::new(value.clone())),
value: None,
simple: true,
range: TextRange::default(),
}
.into()
}

/// Match the `defaults` keyword in a `NamedTuple(...)` call.
fn match_defaults(keywords: &[Keyword]) -> Result<&[Expr]> {
let defaults = keywords.iter().find(|keyword| {
if let Some(arg) = &keyword.arg {
arg == "defaults"
} else {
false
}
});
match defaults {
Some(defaults) => match &defaults.value {
Expr::List(ast::ExprList { elts, .. }) => Ok(elts),
Expr::Tuple(ast::ExprTuple { elts, .. }) => Ok(elts),
_ => bail!("Expected defaults to be `Expr::List` | `Expr::Tuple`"),
},
None => Ok(&[]),
}
}

/// Create a list of property assignments from the `NamedTuple` arguments.
fn create_properties_from_args(args: &[Expr], defaults: &[Expr]) -> Result<Vec<Stmt>> {
fn create_properties_from_args(args: &[Expr]) -> Result<Vec<Stmt>> {
let Some(fields) = args.get(1) else {
let node = Stmt::Pass(ast::StmtPass {
range: TextRange::default(),
Expand All @@ -151,16 +128,8 @@ fn create_properties_from_args(args: &[Expr], defaults: &[Expr]) -> Result<Vec<S
});
return Ok(vec![node]);
}
let padded_defaults = if elts.len() >= defaults.len() {
std::iter::repeat(None)
.take(elts.len() - defaults.len())
.chain(defaults.iter().map(Some))
} else {
bail!("Defaults must be `None` or an iterable of at least the number of fields")
};
elts.iter()
.zip(padded_defaults)
.map(|(field, default)| {
.map(|field| {
let Expr::Tuple(ast::ExprTuple { elts, .. }) = &field else {
bail!("Expected `field` to be `Expr::Tuple`")
};
Expand All @@ -180,9 +149,7 @@ fn create_properties_from_args(args: &[Expr], defaults: &[Expr]) -> Result<Vec<S
if is_dunder(property) {
bail!("Cannot use dunder property name: {}", property)
}
Ok(create_property_assignment_stmt(
property, annotation, default,
))
Ok(create_property_assignment_stmt(property, annotation))
})
.collect()
}
Expand Down Expand Up @@ -228,9 +195,19 @@ pub(crate) fn convert_named_tuple_functional_to_class(
return;
};

let properties = match match_defaults(keywords)
.and_then(|defaults| create_properties_from_args(args, defaults))
{
// Ignore `NamedTuple` calls containing both a list of fields and keywords:
// ```
// NamedTuple(
// "MyType",
// [("a", int), ("b", str)],
// defaults=[0, ""],
// )
// ```
if args.len() > 1 && !keywords.is_empty() {
return;
}
harupy marked this conversation as resolved.
Show resolved Hide resolved

let properties = match create_properties_from_args(args) {
Ok(properties) => properties,
Err(err) => {
debug!("Skipping `NamedTuple` \"{typename}\": {err}");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,37 +23,6 @@ UP014.py:5:1: UP014 [*] Convert `MyType` from `NamedTuple` functional to class s
7 9 | # with default values as list
8 10 | MyType = NamedTuple(

UP014.py:8:1: UP014 [*] Convert `MyType` from `NamedTuple` functional to class syntax
|
7 | # with default values as list
8 | / MyType = NamedTuple(
9 | | "MyType",
10 | | [("a", int), ("b", str), ("c", list[bool])],
11 | | defaults=["foo", [True]],
12 | | )
| |_^ UP014
13 |
14 | # with namespace
|
= help: Convert `MyType` to class syntax

ℹ Suggested fix
5 5 | MyType = NamedTuple("MyType", [("a", int), ("b", tuple[str, ...])])
6 6 |
7 7 | # with default values as list
8 |-MyType = NamedTuple(
9 |- "MyType",
10 |- [("a", int), ("b", str), ("c", list[bool])],
11 |- defaults=["foo", [True]],
12 |-)
8 |+class MyType(NamedTuple):
9 |+ a: int
10 |+ b: str = "foo"
11 |+ c: list[bool] = [True]
13 12 |
14 13 | # with namespace
15 14 | MyType = typing.NamedTuple("MyType", [("a", int), ("b", str)])

UP014.py:15:1: UP014 [*] Convert `MyType` from `NamedTuple` functional to class syntax
|
14 | # with namespace
Expand Down
Loading