Search code examples
pythondocstringf-string

can you define __doc__ directly?


I would like my docstring to be an f-string to put information on, but if I try to do that it isn't showed when you type foo.__doc__ or help(foo), so I tried the following:

used .format() which didn't register as a docstring

tried to do self.__doc__ = f"""...""", but it still didn't work:

def foo():
    self.__doc__ = f"""foo() is a function."""
    pass

I read on a site that it was possible to define the docstring without just putting a docstring at the beginning but it didn't say how.

How shall I start?


Solution

  • __doc__ is just an attribute. You can define it after defining your class / function / method :

    def func():
        pass
    
    func.__doc__ = f"My function doc using fstring"
    
    class Myclass:
    
        def my_method():
            pass
    
        my_method.__doc__ = f"My method doc using string"
    
    Myclass.__doc__ = f"My class doc using fstring"
    

    Calling help() on either func, MyClass or my_method will display your string.