1. 3

Doesn’t really need a video, but I forgot that I stumbled into this oddity of Python2 and the getitem operator.

  1.  

  2. 2

    Someone please explain this one. I’m going crazy.

    edit: BTW - same behaviour on python3 (3.4.4).

    1. 2

      For those that can’t stand video for reading code, the code in question is:

      class A(object):
          def __getitem__(self, item):
              print item
              return item
      
      a = A()
      if "A" in a:
          print "YEP"
      

      A few things to remember:

      __getitem__(...)
          x.__getitem__(y) <==> x[y]
      

      With that in mind, remember that "a" in x is roughly equivalent to:

      i = 0
      try:
          while True:
              if x[i] == "a":
                  return True
              else:
                  i += 1
      except IndexError:
          return False
      

      The original A implementation never bothers to validate the position of getitem