[Python] correct way to "porting" docstrings of other methods/functions/objects into a class?

Discussão em 'Python' iniciado por Stack, Julho 11, 2025.

  1. Stack

    Stack Membro Participativo

    Here is what I am doing:

    class Foo:
    def __init__(self, **kwargs):
    """
    docstring of Foo.
    """
    self.sum = bar(**kwargs)
    __init__.__doc__ += bar.__doc__

    def bar(a, b):
    """
    docstring of bar.
    a: int
    b: int
    """
    print(a+b)


    What I wanted to do: There are some calculations defined in bar. The class Foo uses bar. I would like to avoid duplicate code, i.e. I would like to avoid writing for example a: int in Foo. Thus I am trying to "port" (is this the right term?) the docstring of bar into Foo by adding that line __init__.__doc__ += bar.__doc__.

    Is this the right way to do this? Am I hacking? Imagine Foo is part of API, whereas bar is the backstage subroutine. What's the correct way of displaying the docstring of bar to the user?

    Continue reading...

Compartilhe esta Página