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

后端 未结 8 1629
無奈伤痛
無奈伤痛 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.

    0 讨论(0)
  • 2020-12-05 00:18

    You've posed your question like a class method rather than a function. Namespaces are important here. For a function, print my_function.__doc__ is fine, as my_function is in the global namespace.

    For a class method, then print self.my_method.__doc__ would be the way to go.

    If you don't want to specify the name of the method, but rather pass a variable to it, you can use the built-in functions hasattr(object,attribute) and getattr(obj,attr), which do as they say, allowing you to pass variables in with strings being the name of a method. e.g.

    class MyClass:
        def fn(self):
            """A docstring"""
            print self.fn.__doc__ 
    
    def print_docstrings(object):
       for method in dir( object ):
           if method[:2] == '__':  # A protected function
               continue
           meth = getattr( object, method )
           if hasattr( meth , '__doc__' ):
               print getattr( meth , '__doc__' )
    
    x = MyClass()
    print_docstrings( x )
    
    0 讨论(0)
提交回复
热议问题