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
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."""
Now isn't that so much nicer?
Top comments (2)
I would rather use stubs, as explained here github.com/python/mypy/wiki/Creati...
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)