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?

Heroku

Deliver your unique apps, your own way.

Heroku tackles the toil — patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

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)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay