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][B004] hasattr replace callable #52096

Merged
merged 1 commit into from
Mar 28, 2023

Conversation

gouzil
Copy link
Member

@gouzil gouzil commented Mar 24, 2023

PR types

Others

PR changes

Others

Describe

hasattr(x, '__call__')改写为 callable(x)前者是不可靠的,(相关文档 builtins - hasattrbuiltins - 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
Copy link

paddle-bot bot commented Mar 24, 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.

@@ -301,7 +301,7 @@ def dyfunc(x):
# NOTE: func may have been decorated.
converted_call = None

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

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
Contributor

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
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

@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