-
Notifications
You must be signed in to change notification settings - Fork 5.6k
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
[CodeStyle][C416][C417] rewrite unnecessary comprehension with function call and use generator instead of map #52140
Conversation
…into codestyle-c416c417
你的PR提交成功,感谢你对开源项目的贡献! |
❌ The PR is not created using PR's template. You can refer to this Demo. |
应该在显眼处说明 PR 的先后 merge 关系 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
不建议这种相似性不高的合在一起,不过这个 PR 就别拆了
另外需要解决下冲突
x = 1 | ||
b = [i for i in array] | ||
b = list(array) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
根据函数名,这里就是用来测试 list comprehension 的,需要回退修改并在配置中 tool.ruff.per-file-ignores
ignore 掉本文件
…into codestyle-c416c417
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM
我在这个 PR 里整理了下配置,并解决了一些增量问题,以收尾 C4 系列
辛苦大佬♥ |
PR types
Others
PR changes
Others
Describe
case 31 case 32
1
modify pyproject.toml:
add C413 C414 C416 C417
2
According https://pypi.org/project/flake8-comprehensions/
C416: Unnecessary <dict/list/set> comprehension - rewrite using <dict/list/set>().
It’s unnecessary to use a dict/list/set comprehension to build a data structure if the elements are unchanged. Wrap the iterable with dict(), list(), or set() instead. For example:
Rewrite {a: b for a, b in iterable} as dict(iterable)
Rewrite [x for x in iterable] as list(iterable)
Rewrite {x for x in iterable} as set(iterable)
C417: Unnecessary map usage - rewrite using a generator expression/<list/set/dict> comprehension.
map(func, iterable) has great performance when func is a built-in function, and it makes sense if your function already has a name. But if your func is a lambda, it’s faster to use a generator expression or a comprehension, as it avoids the function call overhead. For example:
Rewrite map(lambda x: x + 1, iterable) to (x + 1 for x in iterable)
Rewrite map(lambda item: get_id(item), items) to (get_id(item) for item in items)
Rewrite list(map(lambda num: num * 2, nums)) to [num * 2 for num in nums]
Rewrite set(map(lambda num: num % 2 == 0, nums)) to {num % 2 == 0 for num in nums}
Rewrite dict(map(lambda v: (v, v ** 2), values)) to {v : v ** 2 for v in values}
In C416:
In C417:
Two rules all can use it.
using rule:✅
auto fix:✅
command as follow: