DEV Community

Cover image for Tiny python docstring tip
Tomer
Tomer

Posted on

23 4

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?

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

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)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay