3

I did a few searches on Python3 and interfaces. I can't seem to find a direct answer on if it's pythonic, or not to use interfaces. I understand that python allows mixins, and allows duck typing. However, they get a set of "requirements" from implementing the interface. What is the decision on Python3 interfaces?

If Interfaces are pythonic then what is the best way to implement them?

Taztingo
  • 1,915
  • 2
  • 27
  • 42
  • [Python doesn't have (and doesn't need) a formal Interface contract](http://stackoverflow.com/questions/372042/difference-between-abstract-class-and-interface-in-python#372121) – OneCricketeer Feb 11 '17 at 02:55
  • 3
    I have always considered them a way to bring Java paradigms into Python. Therefore I do not consider them pythonic at all. – Klaus D. Feb 11 '17 at 02:55
  • Look up "duck typing". Interfacing is different than in many other languages. – martineau Feb 11 '17 at 02:57
  • @martineau Thanks for helping me fix the way I described my question. – Taztingo Feb 11 '17 at 03:15
  • 1
    You're welcome. Because of duck typing and the some of other reasons you mention in your question, Python doesn't determine suitability from an object's type—nor does it provide explicit language support for protocols or interfaces—so the practice of them with it is not widespread (and also why you're not finding a lot of information about it). See the [Protocols and Interfaces](https://en.wikipedia.org/wiki/Duck_typing#Protocols_and_Interfaces) section in the Wikipedia article on [Duck Typing](https://en.wikipedia.org/wiki/Duck_typing). – martineau Feb 11 '17 at 13:57

1 Answers1

1

While Python 2 and 3 supports this type of functionality via nominal subtyping (mixins) and abstract base classes, if you're using type annotations, PEP 544 introduces the concept of static duck typing with Protocol. Similar to Swift protocols or Java interfaces, Protocol defines an interface for subtypes (optionally including default implementations for properties and methods).

You can use Protocols now in all Python versions (except 3.5.0) by importing the typing-extensions module.

followben
  • 9,067
  • 4
  • 40
  • 42