In an effort to apply SOLID principles to a Python project that has grown organically and is in need of re-factoring, I am trying to understand how the Interface Segregation Principle can be applied to the Python language, when Interfaces don't exist as a language feature?
An interface is something that you can type hint against, literally in source code or simply informally in documentation. Python 3 supports function annotations, 3.5+ actual type hints, and even if all that wasn't there, you could still informally type hint simply in the documentation. A type hint simply says that a specific parameter is expected to have specific characteristics.
In more concrete terms:
interface Foo {
string public function bar();
}
function baz(Foo obj) { .. }
All this does is declare that whatever parameter is passed into baz
shall be an object with a method bar
which takes no arguments and returns a string. Even if Python did not implement anything at the language level to enforce this, you can still declare these things any number of ways.
Python does support two important things though: abstract classes and multiple inheritance.
Instead of interface Foo
, in Python you do this:
import abc
class Foo(abc.ABC):
@abc.abstractmethod
def bar() -> str:
pass
Instead of implements Foo
, you do:
class MyClass(Foo):
def bar() -> str:
return 'string'
Instead of function baz(Foo obj)
, you do:
def baz(obj: Foo):
obj.bar()
Due to the multiple inheritance feature, you can segregate your interfaces/abstract classes as finely as you like.
Python is based on the duck-typing principle, so instead of enforcing all this through interface declarations and inheritance, it's usually more loosely defined in terms of "parameter must be an iterable" and such, and the caller simply needs to ensure that the arguments are iterable. Abstract classes and function annotations, coupled with the right development tools, can aid developers in conforming to such contracts at various levels of enforcement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With