I am trying to dynamically assign a function to __del__ of an instance of a class so that it gets called when using dir() on that object. I need __dir__ to be unique for each instance of the class. As a stripped down example, I have tried:
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__()
This prints:
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
in __dir__
['bar']
If I instead do this:
class Foo(object):
def __dir__(self):
print "in __dir__"
return ['bar']
foo = Foo()
print dir(foo)
that outputs:
in __dir__
['bar']
as expected, but can not be customized for each instance of the class. Any ideas?
Ok, based on your comment I worked things a bit. I think this might be closer to the behavior you’re looking for. Calling dir with no args gives all the names in the local scope and calling it on
__class__gives all class names. This ignores the defined__dir__which can be called later on. I’m curious what you’re using this for, maybe there is a simpler way to get the intended behavior?