How to print Docstring of python function from inside the function itself?

后端 未结 8 1641
無奈伤痛
無奈伤痛 2020-12-04 23:26

I want to print the docstring of a python function from inside the function itself. for eg.

def my_function(self):
  \"\"\"Doc string for my function.\"\"\"
         


        
8条回答
  •  情话喂你
    2020-12-05 00:10

    There's quite a simple method for doing this that nobody has mentioned yet:

    import inspect
    
    def func():
        """Doc string"""
        print inspect.getdoc(func)
    

    And this does what you want.

    There's nothing fancy going on here. All that's happening is that by doing func.__doc__ in a function defers attribute resolution long enough to have looking up __doc__ on it work as you'd expect.

    I use this with docopt for console script entry points.

提交回复
热议问题