Although checking attributes in the __dict__ property is very quick, you cannot use this for methods since they do not appear in the __dict__ hash. However, you can resort to a hacker workaround in your class if the performance is so critical:
class Test(): def __init__():
Then check the method as:
t = Test() 'custom_method' in t.__dict__
Time comparison with getattr :
>>%timeit 'custom_method' in t.__dict__ 55.9 ns ± 0.626 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) >>%timeit getattr(t, 'custom_method', None) 116 ns ± 0.765 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
Not that I encouraged this approach, but it seems to work.
[EDIT] The performance improvement is even higher if the method name is not in this class:
>>%timeit 'rubbish' in t.__dict__ 65.5 ns ± 11 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) >>%timeit getattr(t, 'rubbish', None) 385 ns ± 12.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Jaroslav Loebl Mar 06 2018-18-06T00: 00Z
source share