Skip to content

Instantly share code, notes, and snippets.

@thasti
Created February 17, 2020 22:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thasti/a2c4e553b39a9d914b34766eb42fb779 to your computer and use it in GitHub Desktop.
Save thasti/a2c4e553b39a9d914b34766eb42fb779 to your computer and use it in GitHub Desktop.
Exception vs instance checking
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"))
~
@eric-wieser
Copy link

Can you also try:

def test3(a):
    meth = getattr(a, "testmethod", None)
    if meth is None:
        return a, 3
    return meth()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment