Skip to content

[CodeStyle][B004] hasattr replace callable - #52096

Merged
SigureMo merged 1 commit into
PaddlePaddle:developfrom
gouzil:codeStyle-b004
Mar 28, 2023
Merged

SigureMo merged 1 commit into
PaddlePaddle:developfrom
gouzil:codeStyle-b004

Conversation

@gouzil

@gouzil gouzil commented Mar 24, 2023 •

Copy link
Copy Markdown
Collaborator

PR types

Others

PR changes

Others

Describe

将hasattr(x, '__call__')改写为 callable(x)前者是不可靠的,(相关文档 builtins - hasattr 、builtins - callable)

B004 Using hasattr(x, '__call__') to test if x is callable is unreliable. If x implements custom __getattr__ or its __call__ is itself not callable, you might get misleading results. Use callable(x) for consistent results.

是否可以引入本 rule:✅ 如上所述,可以引入
是否可引入自动修复:❌手动修复

修复方法如下:

将python/paddle/jit/dy2static/convert_call_func.py 文件下的

elif hasattr(func, '__class__') and hasattr(func.__class__, '__call__'):

修改为

elif hasattr(func, '__class__') and callable(func.__class__):

Related links

@paddle-bot

paddle-bot Bot commented Mar 24, 2023

Copy link
Copy Markdown

你的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.

converted_call = None

elif hasattr(func, '__class__') and hasattr(func.__class__, '__call__'):
elif hasattr(func, '__class__') and callable(func.__class__):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@Aurelius84 求帮看看这里的修改是否算是一种改进,或者是否会导致出现一些边界 case,我这边看了下觉得改不改区别不大

callable(x) 和 hasattr(x, "__call__") 对比可见 https://stackoverflow.com/questions/16388059/using-callablex-vs-hasattrx-call

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

可以改为callable,似乎比hasattr语义更明确一些:

class A(object):
    def __getattr__(self, name):
        return name
    

a = A()

print(hasattr(a, "__call__"))  # True
print(callable(a))  # False

@SigureMo SigureMo closed this Mar 28, 2023
@SigureMo SigureMo reopened this Mar 28, 2023

@SigureMo SigureMo left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM

@SigureMo
SigureMo merged commit 4118ab8 into PaddlePaddle:develop Mar 28, 2023
@gouzil
gouzil deleted the codeStyle-b004 branch May 15, 2023 14:47
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.

4 participants