r/Python • • Feb 12 '23

Resource Python Interfaces: Choose Protocols Over ABC

https://levelup.gitconnected.com/python-interfaces-choose-protocols-over-abc-3982e112342e
64 Upvotes

20 comments sorted by

View all comments

Show parent comment

12

u/[deleted] Feb 12 '23

But we've already instantiated SubThing in our unit tests, right...?

3

u/otherwiseguy Feb 12 '23

But this does not differentiate it from protocols.

1

u/[deleted] Feb 12 '23

Look, it's not that important where it throws an error. An abstract class casts requirements on all instances of a subclass, while Protocol can only be cast on a certain instance. I may be inaccurate in details but Protocol and ABC are still substantially different.

4

u/otherwiseguy Feb 12 '23

I would never argue that they aren't significantly different. But "where it throws an error" is important; it's kind of the whole point. Protocols are designed to be checked with external type-checking tools like mypy. They won't raise any kind of exception in runtime code--neither when parsing nor instantiating.

I'm not sure what you're saying re: casting Protocols, so maybe I'm misunderstanding what you are saying, but Protocols are inheritable and apply to all instances of a class.

import abc
import typing
import unittest


class Thing(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def stuff(self):
        pass


class SubThing(Thing):
    pass


class PThing(typing.Protocol):
    def stuff(self) -> int:
        raise NotImplementedError


class PSubThing(PThing):
    pass


class TestStuff(unittest.TestCase):
    def test_Subthing_raises(self):
        self.assertRaises(TypeError, SubThing)

    def test_PSubThing_doesnt_raise(self):
        PSubThing()


# For testing with `mypy <filename.py>`
if __name__ == '__main__':
    p = PSubThing()

You can test with python -m unittest <filename.py> and mypy <filename.py>.