Metaclass conundrum - binding value from an outer scope
Peter Otten
__peter__ at web.de
Thu Apr 20 16:19:45 EDT 2017
Skip Montanaro wrote:
> For various reasons, I have a class which delegates much functionality to
> a singleton instance of another class (exposed by pybind11) instead of
> inheriting from that class. So, the construction looks like this (this is
> in Python 2.7):
>
> from someothermodule import SomeOtherClass as _SomeOtherClass
>
> class SomeClass(object):
> _instance = None
>
> def __init__(self):
> if self.__class__._instance is None:
> self._instance = _SomeOtherClass.instance()
>
> def __getattr__(self, key):
> return getattr(self._instance, key)
>
> ... and so on ...
>
> If someone tries help(SomeClass) or dir(SomeClass) today, none of the
> attributes or docstrings defined in SomeOtherClass are shown.
If being helpful really is the only purpose of the metaclass you can
implement a SomeClass.__dir__() method instead:
def __dir__(self):
names = dir(self._instance)
# <snip whatever post-processing you want>
return names
More information about the Python-list
mailing list