Setting a dynamic type docstring in Python 3

I am creating several classes dynamically and I want them to have different docstrings. I have:

def make_class(class_docstring): class X: pass X.__doc__ = class_docstring return X 

This did not work because docstrings are read-only. Then I tried:

 def make_class(class_name, class_docstring): class X: def __init__(self): super().__init__() d = {'__doc__': class_docstring} d.update(X.__dict__) return type(class_name, (), d) ClassName = make_class( 'ClassName', """ Some docstring... """) 

which worked until he had to call super .

What is the correct way to dynamically set the docstring attribute?

+4
source share
1 answer

You can set docstring inside the class.

 >>> def make_class(class_docstring): ... class X: ... __doc__ = class_docstring ... return X ... >>> x = make_class('test doc') >>> x <class '__main__.X'> >>> xx = x() >>> xx.__doc__ 'test doc' 

I'm not sure why your second attempt is not working.

+5
source

Source: https://habr.com/ru/post/1381409/


All Articles