File: nasty_eq_vs_dict.py

package info (click to toggle)
pypy 5.6.0%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 97,040 kB
  • ctags: 185,069
  • sloc: python: 1,147,862; ansic: 49,642; cpp: 5,245; asm: 5,169; makefile: 529; sh: 481; xml: 232; lisp: 45
file content (47 lines) | stat: -rw-r--r-- 1,046 bytes parent folder | download | duplicates (29)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# from http://mail.python.org/pipermail/python-dev/2001-June/015239.html

# if you keep changing a dictionary while looking up a key, you can
# provoke an infinite recursion in C

# At the time neither Tim nor Michael could be bothered to think of a
# way to fix it.

class Yuck:
    def __init__(self):
        self.i = 0

    def make_dangerous(self):
        self.i = 1

    def __hash__(self):
        # direct to slot 4 in table of size 8; slot 12 when size 16
        return 4 + 8

    def __eq__(self, other):
        if self.i == 0:
            # leave dict alone
            pass
        elif self.i == 1:
            # fiddle to 16 slots
            self.__fill_dict(6)
            self.i = 2
        else:
            # fiddle to 8 slots
            self.__fill_dict(4)
            self.i = 1

        return 1

    def __fill_dict(self, n):
        self.i = 0
        dict.clear()
        for i in range(n):
            dict[i] = i
        dict[self] = "OK!"

y = Yuck()
dict = {y: "OK!"}

z = Yuck()
y.make_dangerous()
print dict[z]