dynamically assigning function to __dir__ of an instance
<p>I am trying to dynamically assign a function to <code>__del__</code> of an instance of a class so that it gets called when using dir() on that object.  I need <code>__dir__</code> to be unique for each instance of the class.  As a stripped down example, I have tried:</p>

<pre><code>import types
class Foo(object):
    def __init__(self, arg):
        def __dir__(self):
            print "in __dir__"
            return [arg]
        self.__dir__ = types.MethodType(__dir__, self, self.__class__)

foo = Foo('bar')
print dir(foo)
print
print foo.__dir__()
</code></pre>

<p>This prints:</p>

<pre><code>['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']

in __dir__
['bar']
</code></pre>

<p>If I instead do this:</p>

<pre><code>class Foo(object):
    def __dir__(self):
        print "in __dir__"
        return ['bar']

foo = Foo()
print dir(foo)
</code></pre>

<p>that outputs:</p>

<pre><code>in __dir__
['bar']
</code></pre>

<p>as expected, but can not be customized for each instance of the class.  Any ideas?</p>
