Created
February 17, 2020 22:29
-
-
Save thasti/a2c4e553b39a9d914b34766eb42fb779 to your computer and use it in GitHub Desktop.
Exception vs instance checking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TestClass: | |
def testmethod(self): | |
return 5, 3 | |
def test(a): | |
try: | |
meth = a.testmethod | |
except AttributeError: | |
return a, 3 | |
else: | |
return meth() | |
def test2(a): | |
if not isinstance(a, TestClass): | |
return a, 3 | |
return a.testmethod() | |
if __name__ == '__main__': | |
import timeit | |
print("Try/Except - Except: %.03f" % timeit.timeit("test(5)", setup="from __main__ import test, TestClass")) | |
print("Try/Except - Else: %.03f" % timeit.timeit("test(TestClass())", setup="from __main__ import test, TestClass")) | |
print("isinstance - No: %.03f" % timeit.timeit("test2(5)", setup="from __main__ import test2, TestClass")) | |
print("isinstance - Yes: %.03f" % timeit.timeit("test2(TestClass())", setup="from __main__ import test2, TestClass")) | |
~ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can you also try: