[BE]: Apply RUF025 dict.fromkeys preview rule (#118637)

Simplifies and optimizes dict construction using the `fromkeys` classmethod ctor. This also makes it really obvious when all the keys will have the same static value, which could be a bug if unintentional. It is also significantly faster than using a dict comprehension. The rule is in preview, but I am adding a forward fix for when it becomes stable.

Pull Request resolved: https://github.com/pytorch/pytorch/pull/118637
Approved by: https://github.com/albanD
This commit is contained in:
Aaron Gokaslan
2024-01-30 20:46:48 +00:00
committed by PyTorch MergeBot
parent e33e88e5bc
commit 1562dae62c
26 changed files with 48 additions and 74 deletions

View File

@ -1066,7 +1066,7 @@ TreeSpec(tuple, None, [*,
all_zeros = py_pytree.tree_map_with_path(
lambda kp, val: val - kp[1].key + kp[0].idx, tree
)
self.assertEqual(all_zeros, [{i: 0 for i in range(10)}])
self.assertEqual(all_zeros, [dict.fromkeys(range(10), 0)])
def test_tree_map_with_path_multiple_trees(self):
@dataclass