DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Tiny python docstring tip
Tomer
Tomer

Posted on

Tiny python docstring tip

When defining interfaces in python using the abc.ABC metaclass, sometimes it gets pretty annoying to have so many empty methods, waiting to be filled in.

import abc
class Requester(abc.ABC):
    @abc.abstractmethod
    def get(self, endpoint:str) -> Response:
        """Sends a GET request."""
        pass

    @abc.abstractmethod
    def post(self, endpoint:str, params:dict) -> Response:
        """Makes a POST request."""
        pass
Enter fullscreen mode Exit fullscreen mode

All these uses of pass always felt pretty ugly to me, and luckily there is a solution!

Because docstrings are simply a string expression in the start of a function - you can just let go of the pass!

import abc
class Requester(abc.ABC):
    @abc.abstractmethod
    def get(self, url:str, url_params:dict) -> Response:
        """Sends a GET request."""

    @abc.abstractmethod
    def post(self, url:str, url_params:dict) -> Response:
        """Makes a POST request."""
Enter fullscreen mode Exit fullscreen mode

Now isn't that so much nicer?

Top comments (2)

Collapse
 
dperetti profile image
Dominique PERETTI

I would rather use stubs, as explained here github.com/python/mypy/wiki/Creati...

Collapse
 
tadaboody profile image
Tomer

Stubs and abstract classes aren't the same thing. Stubs annotate existing classes/interfaces/methods helping mypy make static checks.
while abstract classes declare new constructs, used to later be inherited from and implemented (with only runtime checks)

Timeless DEV post...

How to write a kickass README

Arguably the single most important piece of documentation for any open source project is the README. A good README not only informs people what the project does and who it is for but also how they use and contribute to it.

If you write a README without sufficient explanation of what your project does or how people can use it then it pretty much defeats the purpose of being open source as other developers are less likely to engage with or contribute towards it.