How to use the docstring in this property example
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Wed Jan 20 23:50:10 EST 2016
On Thursday 21 January 2016 15:00, Robert wrote:
> Hi,
>
> I read below code snippet on link:
> https://docs.python.org/2/library/functions.html#property
Property docstrings are hard to get to. But with the class C you gave, this
works in the interactive interpreter:
help(C.__dict__['x'])
displays:
I'm the 'x' property.
C.__dict__['x'] will return the property object itself, without running the
getter or setter, so you can access the dostring:
py> C.__dict__['x']
<property object at 0xb7171d9c>
py> C.__dict__['x'].__doc__
"I'm the 'x' property."
But what happens if you inherit the property from some other class?
py> class D(C): pass
...
py> class E(D): pass
...
py> E.__dict__['x']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'x'
In Python 3, you can use the inspect module:
py> obj = inspect.getattr_static(E, 'x')
py> inspect.getdoc(obj)
"I'm the 'x' property."
but in Python 2, you may need to walk the class's MRO by hand. Something
like this:
def getattr_static(obj, name):
if isinstance(obj, type):
for cls in obj.__mro__:
if name in cls.__dict__:
return cls.__dict__[name]
--
Steve
More information about the Python-list
mailing list