Ogen
Ogen

Reputation: 6709

What is the purpose of base classes in Python if you're already referring to the implementation classes consistently

I have a bunch of python classes that are responsible for validating files like so:

All of these classes define a validate_file(path) and validate_string(string) function.

In the client code of my application, I store all of these validators in an array and I iterate through all of them and call the methods on them in exactly the same way.

Is there a purpose in my case of defining a base "validator" class which defines these methods as abstract? How can I benefit from making these individual classes adhere to the base class? Or maybe in other words, what features would be unlocked if I had a base class with all of these validators implementing it?

Upvotes: 1

Views: 509

Answers (2)

Yann Vernier
Yann Vernier

Reputation: 15877

Base classes in Python serve to share implementation details and document likenesses. We don't need to use a common base class for things that function similarly though, as we use protocols and duck typing. For these validation functions, we might not have a use for a class at all; Java is designed to force people to put everything inside classes, but if all you have in your class is one static method, the class is just noise. Having a common superclass would enable you to check dynamically for that using isinstance, but then I'd really wonder why you're handling them in a context where you don't know what they are. For a programmer, the common word in the function name is probably enough.

Upvotes: 2

ShadowRanger
ShadowRanger

Reputation: 155323

If you ever write code that needs to process mixed types, some of which might define the API method, but which shouldn't be considered "validators", having a common base class for "true" validators might be helpful for checking types ahead of time and only processing the "true" validators, not just "things that look like validators". That said, the more complex the method name, the less likely you are to end up with this sort of confusion; the odds of a different type implementing a really niche method name by coincidence are pretty small.

That said, that's a really niche use case. Often, as you can see, Python's duck-typing behavior is good enough on its own; if there is no common functionality between the different types, the only meaningful advantages to having the abstract base class are for the developer, not the program itself:

  1. Having a common point of reference for the API consumer makes it clear what methods they can expect to have access too
  2. For actual ABCs with @abstractmethod decorated methods, it provides a definition-time check for subclasses, making it impossible for maintainers to omit a method by accident

Upvotes: 3

Related Questions