4

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

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

That didn't 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 it had to call super.

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

2
  • Your first approach works perfectly fine. Why do you think doc strings are read-only? They aren't. Commented Nov 16, 2011 at 1:20
  • That is, in Python 2.x at least. Are you using Python 3? Commented Nov 16, 2011 at 1:21

1 Answer 1

5

You can set the 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 2nd attempt is failing.

Sign up to request clarification or add additional context in comments.

3 Comments

The second attempt fails because the call to super() is binding to the type X (it's being translated to super(X)) and then the method is being copied to the dynamically-created type, which doesn't have X in its __mro__.
Would it be okay for me to use: globals()[class_name] = X instead of return X so that I can just write make_class('name', 'docstring') instead of name = make_class(…?
@NeilG: It might work, but injecting things into globals is almost always bad practice. It's much clearer to use name = ... .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.