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

[CodeStyle][C401&C402] replace unnecessary generator set and dict #51845

Conversation

Ainavo
Copy link
Contributor

@Ainavo Ainavo commented Mar 20, 2023

PR types

Others

PR changes

Others

Describe

C401 将生成器中的 set() 替换成 {},使 python 代码更易理解,同时提升代码运行效率,具体如下:

It is unnecessary to use set around a generator expression, since there are equivalent comprehensions for these types. Using a comprehension is clearer and more idiomatic.
Examples

set(f(x) for x in foo) #这里相当于先创建 generator `(f(x) for x in foo)` 之后在调用 `set` 转换成集合。

Use instead:

{f(x) for x in foo} #这里直接创建了 set comprehension,可以省去一步函数的调用,因此可以优化性能。

Notes:可以通过调用 dis 模块查看字节码。

import dis

dis.dis(compile("set(f(x) for x in foo)", "<string>", "exec"))

dis.dis(compile("{f(x) for x in foo}", "<string>", "exec"))

—— unnecessary-generator-set (C401)

C402 将生成器中的 dict((x, f(x)) for x in foo) 替换成 {x: f(x) for x in foo},使 python 代码更易理解,同时提升代码运行效率,具体如下:

It is unnecessary to use dict around a generator expression, since there are equivalent comprehensions for these types. Using a comprehension is clearer and more idiomatic.
Examples

dict((x, f(x)) for x in foo) #这里相当于先创建 generator `((x, f(x)) for x in foo)` 之后在调用 `dict` 转换成字典。

Use instead:

{x: f(x) for x in foo} #这里直接创建了 dict comprehension,可以省去一步函数的调用,因此可以优化性能。

Notes:可以通过调用 dis 模块查看字节码。

import dis

dis.dis(compile("dict((x, f(x)) for x in foo)", "<string>", "exec"))

dis.dis(compile("{x: f(x) for x in foo}", "<string>", "exec"))

—— unnecessary-generator-dict (C402)

参考链接:

Tracking issue:

Copy link
Member

@SigureMo SigureMo left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

#51839 没修改配置,可以在之后 PR 里一并修改

@paddle-bot paddle-bot bot added the contributor External developers label Mar 20, 2023
@Ainavo Ainavo changed the title [CodeStyle][C401&C402] remove unnecessary generator set and dict [CodeStyle][C401&C402] replace unnecessary generator set and dict Mar 21, 2023
@SigureMo
Copy link
Member

PR-CI-Coverage 卡住一天没动了,可以 re-run 下 @Ainavo

@SigureMo
Copy link
Member

PR-CI-Coverage 有单测超时了,再 re-run 一下吧 @Ainavo

@luotao1 luotao1 merged commit cdc5896 into PaddlePaddle:develop Mar 21, 2023
@Ainavo Ainavo deleted the remove_unnecessary_generator_set_and_dict branch March 21, 2023 12:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
contributor External developers
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants