How to get different documentation on help() for different objects in python

Viewed 52

I have a class with help message, which should depends on input argument for __init__, e.g.:

class A:
    '''
    {}
    '''
    def __init__(self, x):
        A.__doc__ = A.__doc__.format(x)

But when I run

x = A("xxxxx")
y = A("yyyyy")
help(x)
help(y)

I get the same messages for both help() calls:

Help on A in module __main__ object:

class A(builtins.object)
 |  xxxxx
 |
:

Is there a way to create different documentation for different objects?

1 Answers

The __doc__ member that gets used in help is the class' __doc__, not the instance's. That means there can be only one. See the data model's special method lookup section:

For custom classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type

I am not familiar with the details, but it also seems the class' __doc__ property can be set only once. That means you will get the docstring you set in the first instance you create. Perhaps someone will know more about this.

An alternative?

So now the question is whether you want a function that behaves the way you described. Since you want a different docstring, I suppose you want different behavior for each instance (otherwise why would you want a different docstring?). That might be clearer if you have a collection of derived classes. If this is not the case, it would help to know the specific problem you are trying to solve.

You could then have a factory method that will create objects of the proper type, given the arguments.

Related