Including a docstring in another docstring

怎甘沉沦 提交于 2021-02-08 12:05:44

问题


Problem: I want to use one docstring in another docstring.

Suppose I have the following snippet:

def window(dimensions: tuple):
    '''
    Function to create an app window and return it

    PARAMETERS
    ----------
    dimensions : tuple
        The width and height of the window to create

    RETURNS
    -------
    display.Window
        Class to implement a screen           # Make this equal to Window.__doc__ 
    '''
    class Window:
        '''
        Class to implement a screen
        '''
        def __init__(self, dimensions: tuple):
            pass
    return Window(dimensions)

I want to automatically set the docstring for window to include the docstring for Window

I read that you can set the docstring manually, like so:

window.__doc__ = "".join((window.__doc__, Window.__doc__))

But it is only executed when the function is called.

Also, I could use decorators, but is there a simpler intuitive way to do this?

Bonus: Is there a way to decide exactly where in the docstring I can include another?

EDIT: So, it looks like there is a duplicate suggestion to this question, but since I specifically asked without decorators, that does make my question somewhat different. Also, my use of nested class in window means that any attempt to change __doc__:

  1. inside of window: will not occur until function is called.
  2. outside of window: will not run as Window is nested.
So this rules both these methods out, as things stand.

But the answer of course has to be one of these. So the answer is a duplicate, not the question. :P

Therefore, I had to restructure my code. See below.


回答1:


Thanks to @aparpara, I found that answer (which didn't show up when I searched it online), and it made me realise there is (possibly?) no solution to my specific question.

Therefore, I had to remove the nested class to be able to access it outside the function.

Here is the final version.

# module display_module.py

class Window:
    '''
    Class to implement pygame's screen
    '''
    def __init__(self, dimensions: tuple):
        pass

def window(dimensions: tuple):
    '''
    Function to create an app window and return it

    PARAMETERS
    ----------
    dimensions : tuple
        The width and height of the window to create

    RETURNS
    -------
    display.Window
        {0}
    '''
    return Window(dimensions)

window.__doc__ = window.__doc__.format(Window.__doc__.strip())

Still open to any answers to the old question!



来源:https://stackoverflow.com/questions/58256881/including-a-docstring-in-another-docstring

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!