
On 23 May 2011 19:16, Michael Foord <fuzzyman@gmail.com> wrote:
Hello all,
I'm looking at implementing __dir__ for a class (mock.Mock as it happens) to include some dynamically added attributes, the canonical use case according to the documentation:
http://docs.python.org/dev/reference/datamodel.html?highlight=__dir__#object...
What I would like to do is report all the "standard attributes", and then add any dynamically created attributes.
So the question is, how do I obtain the "standard list" (the list that dir would normally report in the absence of a custom __dir__ implementation)?
There is no object.__dir__ (despite the fact that this is how it is documented...) and obviously calling dir(self) within __dir__ is doomed to failure.
The best I have come up with is:
def __dir__(self): return dir(type(self)) + list(self.__dict__) + self._get_dynamic_attributes()
Better version which orders and removes duplicates: return sorted(set((dir(type(self)) + list(self.__dict__) + self._get_dynamic_attributes()))
This works (absent multiple inheritance), but it would be nice to just be able to do:
def __dir__(self): standard = super().__dir__() return standard + self._get_dynamic_attributes()
Moving the relevant parts of the implementation of dir into object.__dir__ would be one way to solve that.
All the best,
Michael Foord
--
May you do good and not evil May you find forgiveness for yourself and forgive others May you share freely, never taking more than you give. -- the sqlite blessing http://www.sqlite.org/different.html
-- http://www.voidspace.org.uk/ May you do good and not evil May you find forgiveness for yourself and forgive others May you share freely, never taking more than you give. -- the sqlite blessing http://www.sqlite.org/different.html