[Python-ideas] Implementing __dir__ (moving dir implementation to object.__dir__?)

Michael Foord fuzzyman at gmail.com
Mon May 23 20:16:44 CEST 2011


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.__dir__

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()

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

-- 

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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20110523/36488a2c/attachment.html>


More information about the Python-ideas mailing list