Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

docstring that works with a Python class property?

I have a class defined below that has a class property called 'prop', and I want the docstring 'this is a property comment' to print out. The current behavior executes the getter for the property and prints 'getter'.

Is there a way to setup the class and its metaclass so I can type 'help(MyClass.prop)' and get the docstring?

class _Metaclass(type):
    @property
    def prop(cls):
        """this is a property comment"""
        print("getter")
        return 1
    @prop.setter
    def prop(cls,value):
        print("setter")

class MyClass(metaclass=_Metaclass):
    """this is a class comment"""
    def func():
        """this is a function comment"""
like image 317
Michael Kelley Avatar asked Feb 09 '26 16:02

Michael Kelley


1 Answers

You have set a property on a metaclass. Thus when you do MyClass.prop you are actually executing the property on the MyClass class object. If this was on a normal class instead of a metaclass the docstring would be correctly defined from the getter method. Metaclasses are to classes as classes are to instances, if that helps you think about what's going on here. You should get the correct docstring from help(_Metaclass.prop).

like image 93
Michael Merickel Avatar answered Feb 12 '26 14:02

Michael Merickel