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][C408][C409][C410] Fix unnecessary <dict/list/tuple> call and unnecessary <list/tuple> passed to <list/tupule>() #51928

Merged
merged 5 commits into from
Mar 23, 2023

Conversation

AndPuQing
Copy link
Contributor

@AndPuQing AndPuQing commented Mar 21, 2023

PR types

Others

PR changes

Others

Describe

C408,移除了非必要的<dict/list/tuple>的调用, 使用 类似于 dict() 比使用空字面量更慢,因为必须在全局范围内查找 dict 的名称以防止其被重新绑定。

就性能而言

>>> from timeit import timeit
>>> timeit("a = {'a': 1, 'b': 2}")
0.06038427300000038
>>> timeit("a = dict(a = 1, b = 2)")
0.0972164400000004

>>> timeit("a = [1,2]")
0.03602197400002183
>>> timeit("a = list([1,2])")
0.11876870599999734

>>> timeit("a = (1,2)")
0.013362353000019311
>>> timeit("a = tuple([1,2])")
0.07062553700001217

反编译结果

>>> def f():
...     return {'a' : 1, 'b' : 2}
... 
>>> def g():
...     return dict(a=1, b=2)
... 
>>> import dis
>>> dis.dis(f)
  2           0 LOAD_CONST               1 (1)
              2 LOAD_CONST               2 (2)
              4 LOAD_CONST               3 (('a', 'b'))
              6 BUILD_CONST_KEY_MAP      2
              8 RETURN_VALUE
>>> dis.dis(g)
  2           0 LOAD_GLOBAL              0 (dict)
              2 LOAD_CONST               1 (1)
              4 LOAD_CONST               2 (2)
              6 LOAD_CONST               3 (('a', 'b'))
              8 CALL_FUNCTION_KW         2
             10 RETURN_VALUE

C409,C410 移除了不必要的 <list/tuple> 传递给了 <list/tuple>() 函数

>>> from timeit import timeit
>>> timeit("a = tuple([1, 2])")
0.07401427399997829
>>> timeit("a = (1, 2)")
0.013548898000067311
  • 是否可以引入本 rule:✅ 如上所述,可以引入
  • 是否可引入自动修复:✅ 转写后不会影响代码的语义,可以引入

修复使用指令如下:

ruff --select C410 . --fix
ruff --select C409 . --fix 
ruff --select C408 . --fix

Related links

SigureMo
SigureMo previously approved these changes Mar 21, 2023
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~

@paddle-bot paddle-bot bot added the contributor External developers label Mar 21, 2023
@luotao1
Copy link
Contributor

luotao1 commented Mar 22, 2023

@AndPuQing 请解决下冲突

@AndPuQing
Copy link
Contributor Author

@AndPuQing 请解决下冲突

Done

@luotao1 luotao1 merged commit cf391b8 into PaddlePaddle:develop Mar 23, 2023
@AndPuQing AndPuQing deleted the ruff/fix-C409 branch March 23, 2023 02:16
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