Should I use interfaces in Python (so my code will be more testable and following good practices)?

softwareengineering.stackexchange https://softwareengineering.stackexchange.com/questions/411665

  •  12-03-2021
  •  | 
  •  

Question

I've never coded in Python. In languages like C# or Java a lot of people write interfaces for (almost) every class so the code can be more easily testable (by implementing IoC) or other reasons and is considered good practice by many.

I'm confused because Python don't have built in interfaces as the other languages I've worked with, but there are some libraries that give similar options.

Is using interfaces considered good practice in Python programmers' world and should I use them?

Was it helpful?

Solution

The type systems of Python on the one hand and C# and Java on the other hand work in a fundamentally different way.

C# and Java use a nominal type system: Two types are the same if they have the same name. Additionally, they use strong typing: assignment (and parameter passing) between references is only allowed if the target type is in the set of types formed by enumerating the source's type and declared sub-types.

Python on the other hand uses a structural type system: Two types are considered compatible if you can do the same operations on them. This is also called duck-typing (if it quacks like a duck and walks like a duck, then you can treat it as a duck).

Furthermore, type declarations for function parameters and return types are a relatively new addition to Python and they are not actively used by the Python runtime environment.

As Python doesn't require the match in type names and doesn't actively check type matches on function calls, there has traditionally been much less incentive to use interface declarations in Python than in C#/Java. And due to the structural typing, there is still no need to explicitly mention a class implements interface X. A function that is documented to need an argument of type X will accept anything that is structurally compatible with X, not just classes that explicitly mention implementing X.

Thus, interfaces in Python are useful documentation tools, but they are not needed to support Dependency Injection or Mocking in testcases, like they are in C# and Java.

Licensed under: CC-BY-SA with attribution
scroll top