Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Interfaces" in Python: Yea or Nay? [closed]

Tags:

So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to the idea.

Just so we're clear, an interface in Python would look something like this:

class ISomething(object):
    def some_method():
        pass
    def some_other_method(some_argument):
        pass

Notice that you aren't passing self to any of the methods, thus requiring that the method be overriden to be called. I see this as a nice form of documentation and completeness testing.

So what is everyone here's opinion on the idea? Have I been brainwashed by all the C# programming I've done, or is this a good idea?

like image 500
Jason Baker Avatar asked Feb 16 '09 02:02

Jason Baker


People also ask

Do interfaces exist in Python?

Unfortunately, Python doesn't have interfaces, or at least, not quite built into the language. Enter Python's abstract base class, or, cutely, ABC. Functionally, abstract base classes let you define a class with abstract methods, which all subclasses must implement in order to be initialized.

Why there are no interfaces in Python?

Python does not have interfaces, but the same functionality can be achieved with the help of abstract base classes and multiple inheritance. The reason for not having interfaces is that Python does not use static typing, so there's no compile-time type checking.

Are interfaces necessary in Python?

As a project grows, the need for a formal Python interface becomes more important as it becomes more difficult to infer return types. This ensures that the concrete class, which implements the interface, overwrites the abstract methods.

Why is interface used in Python?

Interface acts as a blueprint for designing classes, so interfaces are implemented using implementer decorator on class. If a class implements an interface, then the instances of the class provide the interface. Objects can provide interfaces directly, in addition to what their classes implement.


1 Answers

I'm not sure what the point of that is. Interfaces (of this form, anyway) are largely to work around the lack of multiple inheritance. But Python has MI, so why not just make an abstract class?

class Something(object):
    def some_method(self):
        raise NotImplementedError()
    def some_other_method(self, some_argument):
        raise NotImplementedError()
like image 93
Ken Avatar answered Oct 05 '22 14:10

Ken