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][B009][B010] use normal property access instead of getattr/setattr #51530

Merged
merged 2 commits into from
Mar 16, 2023

Conversation

SigureMo
Copy link
Member

@SigureMo SigureMo commented Mar 12, 2023

PR types

Others

PR changes

Others

Describe

getattr(x, 'attr') 形式的代码直接替换为 x.attr,因为在不使用第三个参数默认值的情况下两者等价(相关文档见 builtins - getattr),前者反而写法繁琐,不易阅读

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised. name need not be a Python identifier (see setattr()).

-- 摘自 getattr 文档描述

setattr(x, 'attr', value) 形式的代码直接替换为 x.attr = value,理由同上

  • 是否可以引入本 rule:✅ 如上所述,可以引入
  • 是否可引入自动修复:✅ 转写后不会影响代码的语义,该规则可视为可靠的自动转写规则,可以引入

修复所使用的命令如下:

# 安装 ruff 0.0.254
pip install ruff==0.0.254
# 确定本 rule 自动修复方案合适,因此直接使用命令自动修复
ruff --select B009 . --fix
ruff --select B010 . --fix
# 自动修复之后重新运行确保没有存量
ruff --select B009 .
ruff --select B010 .

Note

  • 本 PR 基于 [CodeStyle] initialize ruff config #51201,需在 [CodeStyle] initialize ruff config #51201 merge 后 merge,现在超过 20 个文件了,待 merge 之后应该就是 19 了
  • 本 PR 为示例 PR,因此同时修改了配置和代码,实际操作可视情况拆分配置和代码修改
  • 对于修改原因一定要加上相关文档链接,比如本 PR 链接到了 getattr 的 Python 文档,其余修改应尽可能链接到对应的官方 Python 文档 / PEP 文档,如果文档中没有相关内容的完整陈述的话,stackoverflow 也可以,不建议链接到第三方博客等链接
  • 使用 autofix 功能后应该先自行 review 一遍,如果认为没有问题(不只是能通过 CI,还要保证代码语义不会修改、性能不会下降)再提交 PR

Related links

@paddle-bot
Copy link

paddle-bot bot commented Mar 12, 2023

你的PR提交成功,感谢你对开源项目的贡献!
请关注后续CI自动化测试结果,详情请参考Paddle-CI手册
Your PR has been submitted. Thanks for your contribution!
Please wait for the result of CI firstly. See Paddle CI Manual for details.

@luotao1 luotao1 self-assigned this Mar 16, 2023
@SigureMo SigureMo force-pushed the ruff/fix-and-config/b009 branch from beb9e20 to c741f00 Compare March 16, 2023 05:01
@SigureMo SigureMo merged commit 2f2b1f2 into PaddlePaddle:develop Mar 16, 2023
@SigureMo SigureMo deleted the ruff/fix-and-config/b009 branch March 16, 2023 17:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants