Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.