Skip to content

Instantly share code, notes, and snippets.

@d3rp
Created August 25, 2019 08:40
Show Gist options
  • Save d3rp/57021f382d16f6fb0f5b50b2dbcc2911 to your computer and use it in GitHub Desktop.
Save d3rp/57021f382d16f6fb0f5b50b2dbcc2911 to your computer and use it in GitHub Desktop.
Class closure (Kind of a gotcha if done by accident)
"""instance variables gotcha"""
class C:
"""Works like a closure because class body is interpreted at import time"""
data = {}
def __init__(self, input):
self.data.update(input)
c = C({'a':'b'})
print(c.data)
# {'a': 'b'}
not_the_same_instance = C({'foo': 'bar'})
print(not_the_same_instance.data)
# {'a': 'b', 'foo': 'bar'}
print(c.data)
# {'a': 'b', 'foo': 'bar'}
class X:
"""methods are interpreted at runtime, so the mutable instance variable won't work as closure"""
def __init__(self, input):
self.data = {}
self.data.update(input)
x = X({'a':'b'})
print(x.data)
# {'a': 'b'}
y = X({'foo': 'bar'})
print(y.data)
# {'foo': 'bar'}
print(x.data)
# {'a': 'b'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment