Skip to content

Instantly share code, notes, and snippets.

@badouralix
Created January 2, 2019 20:50
Show Gist options
  • Select an option

  • Save badouralix/21923225216a7f89a43ff81720dbe71b to your computer and use it in GitHub Desktop.

Select an option

Save badouralix/21923225216a7f89a43ff81720dbe71b to your computer and use it in GitHub Desktop.
PoC of an interesting buggy behavior in Python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
PoC of an interesting buggy behavior in Python. Also works in python2.
$ ./mutable-dict-keys.py
{Mutable(0): 'value'} is consistent
{Mutable(1): 'value'} is not consistent
"""
class Mutable():
__slots__ = ['attr']
def __init__(self, attr=0):
self.attr = attr
def __hash__(self):
return hash((self.attr))
def __repr__(self):
return "%s(%s)" % (
self.__class__.__name__,
self.attr,
)
def change(self):
self.attr += 1
def check(d):
for key in d:
if key not in d:
print("%s is not consistent" % d)
return False
print("%s is consistent" % d)
return True
def main():
dic = dict()
key = Mutable()
dic[key] = "value"
check(dic) # Return True
key.change()
check(dic) # Return False
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment