Skip to content

Instantly share code, notes, and snippets.

@rmst
Last active April 19, 2022 21:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmst/78b2b0f56a3d9ec13b1ec6f3bd50aa9c to your computer and use it in GitHub Desktop.
Save rmst/78b2b0f56a3d9ec13b1ec6f3bd50aa9c to your computer and use it in GitHub Desktop.
Python closures vs methods
from timeit import timeit
import inspect
def t():
for f in inspect.stack():
print(f.function)
t()
s = """
class Object:
def __init__(self):
pass
def A(x):
self = Object()
def bar(y):
return x+y
self.bar = bar
return self
class B:
def __init__(self, x):
self.x = x
def bar(self, y):
return self.x + y
a = A(3)
b = B(3)
"""
a = """
a = A(3)
"""
b = """
b = B(3)
"""
c = """a.bar(4)"""
d = """b.bar(4)"""
print(timeit(a, s, number=1000000))
print(timeit(b, s, number=1000000))
print(timeit(c, s, number=1000000))
print(timeit(d, s, number=1000000))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment