title: Workaround for equality of nested functions
body: <p>I have a nested function that I'm using as a callback in <code>pyglet</code>:</p>
  
  <pre><code>def get_stop_function(stop_key):
      def stop_on_key(symbol, _):
          if symbol == getattr(pyglet.window.key, stop_key):
              pyglet.app.exit()
      return stop_on_key
  
  pyglet.window.set_handler('on_key_press', get_stop_function('ENTER'))
  </code></pre>
  
  <p>But then I run into problems later when I need to reference the nested function again:</p>
  
  <pre><code>pyglet.window.remove_handler('on_key_press', get_stop_function('ENTER'))
  </code></pre>
  
  <p>This doesn't work because of the way python treats functions:</p>
  
  <pre><code>my_stop_function = get_stop_function('ENTER')
  my_stop_function is get_stop_function('ENTER')  # False
  my_stop_function == get_stop_function('ENTER')  # False
  </code></pre>
  
  <p>Thanks to two <a href="https://stackoverflow.com/questions/18216597/how-should-functions-be-tested-for-equality-or-identity">similar</a> <a href="https://stackoverflow.com/questions/15977808/why-dont-methods-have-reference-equality">questions</a> I understand what is going on but I'm not sure  what the workaround is for my case. I'm looking through the <a href="https://code.google.com/p/pyglet/source/browse/pyglet/event.py" rel="nofollow noreferrer">pyglet source code</a> and it looks like pyglet uses equality to find the handler to remove.</p>
  
  <p>So my final question is: how can I override the inner function's <code>__eq__</code> method (or some other dunder) so that identical nested functions will be equal?</p>
  
  <p>(Another workaround would be to store a reference to the function myself, but that is duplicating pyglet's job, will get messy with many callbacks, and anyways I'm curious about this question!)</p>
  
  <p>Edit: actually, in the questions I linked above, it's explained that methods have value equality but not reference equality. With nested functions, you don't even get value equality, which is all I need.</p>
  
  <p>Edit2: I will probably accept Bi Rico's answer, but does anyone know why the following doesn't work:</p>
  
  <pre><code>def get_stop_function(stop_key):
      def stop_on_key(symbol, _):
          if symbol == getattr(pyglet.window.key, stop_key):
              pyglet.app.exit()
      stop_on_key.__name__ = '__stop_on_' + stop_key + '__'
      stop_on_key.__eq__ = lambda x: x.__name__ == '__stop_on_' + stop_key + '__'
      return stop_on_key
  
  get_stop_function('ENTER') == get_stop_function('ENTER')  # False
  get_stop_function('ENTER').__eq__(get_stop_function('ENTER'))  # True
  </code></pre>