There's a bit of a story behind interfaces in Python. The original attitude, which held sway for many years, is that you don't need them: Python works on the EAFP (easier to ask forgiveness than permission) principle. That is, instead of specifying that you accept an, I don't know, ICloseable object, you simply try to close the object when you need to, and if it raises an exception then it raises an exception.

So in this mentality you would just write your classes separately, and use them as you will. If one of them doesn't conform to the requirements, your program will raise an exception; conversely, if you write another class with the right methods then it will just work, without your needing to specify that it implements your particular interface.

This works pretty well, but there are definite use cases for interfaces, especially with larger software projects. The final decision in Python was to provide the abc module, which allows you to write abstract base classes i.e. classes that you can't instantiate unless you override all their methods. It's your decision as to whether you think using them is worth it.

The PEP introducing ABCs explain much better than I can:

In the domain of object-oriented programming, the usage patterns for interacting with an object can be divided into two basic categories, which are 'invocation' and 'inspection'.

Invocation means interacting with an object by invoking its methods. Usually this is combined with polymorphism, so that invoking a given method may run different code depending on the type of an object.

Inspection means the ability for external code (outside of the object's methods) to examine the type or properties of that object, and make decisions on how to treat that object based on that information.

Both usage patterns serve the same general end, which is to be able to support the processing of diverse and potentially novel objects in a uniform way, but at the same time allowing processing decisions to be customized for each different type of object.

In classical OOP theory, invocation is the preferred usage pattern, and inspection is actively discouraged, being considered a relic of an earlier, procedural programming style. However, in practice this view is simply too dogmatic and inflexible, and leads to a kind of design rigidity that is very much at odds with the dynamic nature of a language like Python.

In particular, there is often a need to process objects in a way that wasn't anticipated by the creator of the object class. It is not always the best solution to build in to every object methods that satisfy the needs of every possible user of that object. Moreover, there are many powerful dispatch philosophies that are in direct contrast to the classic OOP requirement of behavior being strictly encapsulated within an object, examples being rule or pattern-match driven logic.

On the other hand, one of the criticisms of inspection by classic OOP theorists is the lack of formalisms and the ad hoc nature of what is being inspected. In a language such as Python, in which almost any aspect of an object can be reflected and directly accessed by external code, there are many different ways to test whether an object conforms to a particular protocol or not. For example, if asking 'is this object a mutable sequence container?', one can look for a base class of 'list', or one can look for a method named '_getitem_'. But note that although these tests may seem obvious, neither of them are correct, as one generates false negatives, and the other false positives.

The generally agreed-upon remedy is to standardize the tests, and group them into a formal arrangement. This is most easily done by associating with each class a set of standard testable properties, either via the inheritance mechanism or some other means. Each test carries with it a set of promises: it contains a promise about the general behavior of the class, and a promise as to what other class methods will be available.

This PEP proposes a particular strategy for organizing these tests known as Abstract Base Classes, or ABC. ABCs are simply Python classes that are added into an object's inheritance tree to signal certain features of that object to an external inspector. Tests are done using isinstance(), and the presence of a particular ABC means that the test has passed.

In addition, the ABCs define a minimal set of methods that establish the characteristic behavior of the type. Code that discriminates objects based on their ABC type can trust that those methods will always be present. Each of these methods are accompanied by an generalized abstract semantic definition that is described in the documentation for the ABC. These standard semantic definitions are not enforced, but are strongly recommended.

Like all other things in Python, these promises are in the nature of a gentlemen's agreement, which in this case means that while the language does enforce some of the promises made in the ABC, it is up to the implementer of the concrete class to insure that the remaining ones are kept.

Answer from Katriel on Stack Overflow
Top answer
1 of 6
81

There's a bit of a story behind interfaces in Python. The original attitude, which held sway for many years, is that you don't need them: Python works on the EAFP (easier to ask forgiveness than permission) principle. That is, instead of specifying that you accept an, I don't know, ICloseable object, you simply try to close the object when you need to, and if it raises an exception then it raises an exception.

So in this mentality you would just write your classes separately, and use them as you will. If one of them doesn't conform to the requirements, your program will raise an exception; conversely, if you write another class with the right methods then it will just work, without your needing to specify that it implements your particular interface.

This works pretty well, but there are definite use cases for interfaces, especially with larger software projects. The final decision in Python was to provide the abc module, which allows you to write abstract base classes i.e. classes that you can't instantiate unless you override all their methods. It's your decision as to whether you think using them is worth it.

The PEP introducing ABCs explain much better than I can:

In the domain of object-oriented programming, the usage patterns for interacting with an object can be divided into two basic categories, which are 'invocation' and 'inspection'.

Invocation means interacting with an object by invoking its methods. Usually this is combined with polymorphism, so that invoking a given method may run different code depending on the type of an object.

Inspection means the ability for external code (outside of the object's methods) to examine the type or properties of that object, and make decisions on how to treat that object based on that information.

Both usage patterns serve the same general end, which is to be able to support the processing of diverse and potentially novel objects in a uniform way, but at the same time allowing processing decisions to be customized for each different type of object.

In classical OOP theory, invocation is the preferred usage pattern, and inspection is actively discouraged, being considered a relic of an earlier, procedural programming style. However, in practice this view is simply too dogmatic and inflexible, and leads to a kind of design rigidity that is very much at odds with the dynamic nature of a language like Python.

In particular, there is often a need to process objects in a way that wasn't anticipated by the creator of the object class. It is not always the best solution to build in to every object methods that satisfy the needs of every possible user of that object. Moreover, there are many powerful dispatch philosophies that are in direct contrast to the classic OOP requirement of behavior being strictly encapsulated within an object, examples being rule or pattern-match driven logic.

On the other hand, one of the criticisms of inspection by classic OOP theorists is the lack of formalisms and the ad hoc nature of what is being inspected. In a language such as Python, in which almost any aspect of an object can be reflected and directly accessed by external code, there are many different ways to test whether an object conforms to a particular protocol or not. For example, if asking 'is this object a mutable sequence container?', one can look for a base class of 'list', or one can look for a method named '_getitem_'. But note that although these tests may seem obvious, neither of them are correct, as one generates false negatives, and the other false positives.

The generally agreed-upon remedy is to standardize the tests, and group them into a formal arrangement. This is most easily done by associating with each class a set of standard testable properties, either via the inheritance mechanism or some other means. Each test carries with it a set of promises: it contains a promise about the general behavior of the class, and a promise as to what other class methods will be available.

This PEP proposes a particular strategy for organizing these tests known as Abstract Base Classes, or ABC. ABCs are simply Python classes that are added into an object's inheritance tree to signal certain features of that object to an external inspector. Tests are done using isinstance(), and the presence of a particular ABC means that the test has passed.

In addition, the ABCs define a minimal set of methods that establish the characteristic behavior of the type. Code that discriminates objects based on their ABC type can trust that those methods will always be present. Each of these methods are accompanied by an generalized abstract semantic definition that is described in the documentation for the ABC. These standard semantic definitions are not enforced, but are strongly recommended.

Like all other things in Python, these promises are in the nature of a gentlemen's agreement, which in this case means that while the language does enforce some of the promises made in the ABC, it is up to the implementer of the concrete class to insure that the remaining ones are kept.

2 of 6
6

I'm not that familiar with Python, but I would hazard a guess that it doesn't.

The reason why interfaces exist in Java is that they specify a contract. Something that implements java.util.List, for example, is guaranteed to have an add() method to conforms to the general behaviour as defined on the interface. You could drop in any (sane) implementation of List without knowing its specific class, call a sequence of methods defined on the interface and get the same general behaviour.

Moreover, both the developer and compiler can know that such a method exists and is callable on the object in question, even if they don't know its exact class. It's a form of polymorphism that's needed with static typing to allow different implementation classes yet still know that they're all legal.

This doesn't really make sense in Python, because it's not statically typed. You don't need to declare the class of an object, nor convince the compiler that methods you're calling on it definitely exist. "Interfaces" in a duck-typing world are as simple as invoking the method and trusting that the object can handle that message appropriately.

Note - edits from more knowledgeable Pythonistas are welcome.

🌐
Real Python
realpython.com › python-interface
Implementing Interfaces in Python: ABCs and Protocols – Real Python
1 month ago - Python doesn’t have a dedicated interface keyword like Java or C#. Instead, it offers two ways to define interfaces: abstract base classes through abc.ABC, and structural interfaces through typing.Protocol.
Discussions

Java Python Integration - Stack Overflow
Another option is to write a C wrapper around that pieces of Python functionality that you need to expose to Java and use it via JVM native plugins. You can ease the pain by going with SWIG SWIG. ... Create a SWIG interface for all method calls from Java to C++. More on stackoverflow.com
🌐 stackoverflow.com
java - Creating and Implementing an interface using Python? - Stack Overflow
I have two (2) questions: Firstly, how do I create the FlyBehavior interface using Python? Secondly, how do I implement the FlyBehavior interface in the FlyWithWings class, using Python (see below)... More on stackoverflow.com
🌐 stackoverflow.com
Using Python from within Java - Stack Overflow
I'm aware of the Jython project, but it looks like this represents a way to use Java and its libraries from within Python, rather than the other way round - am I wrong about this? If not, what would be the best method to interface between Java and Python, such that (ideally) I can call a method ... More on stackoverflow.com
🌐 stackoverflow.com
Python interfaces? What is it for? Or it is there because a Java developer happens to write Python?
In Zope it is a part of larger structure where classes are pluggable by configuration. So you can have user object with name, email and password stored in a database or you can change a configuration and have the user object look up the user data in LDAP etc. So Zope is 100% configurable in that regard. the contract for new objects and classes is that they follow the interface, and declare to do so. In older versions you could somewhat do the same, but it worked by convention. And only for one type at a time. So a class can implement an interface and the system can understand it. Making it possible to do something like: class User: implements(UserData) implements(PresentationPage) implements(SQLStorage) It is a technically really clever solution that I have really disliked using in practice. More on reddit.com
🌐 r/Python
14
2
July 15, 2016
🌐
Quora
quora.com › Is-there-an-equivalent-to-interfaces-à-la-Java-in-Python
Is there an equivalent to interfaces (à la Java) in Python? - Quora
Answer (1 of 3): Not directly - but you can write an abstract class which defines the methods which your concrete classes need to have. You can then use multiple inheritance to ensure that your concrete class has supports the functionality you need - Example : To build a Abstract base class for...
Top answer
1 of 12
38

Why not use Jython? The only downside I can immediately think of is if your library uses CPython native extensions.

EDIT: If you can use Jython now but think you may have problems with a later version of the library, I suggest you try to isolate the library from your app (e.g. some sort of adapter interface). Go with the simplest thing that works for the moment, then consider JNI/CPython/etc if and when you ever need to. There's little to be gained by going the (painful) JNI route unless you really have to.

2 of 12
21

Frankly most ways to somehow run Python directly from within JVM don't work. They are either not-quite-compatible (new release of your third party library can use python 2.6 features and will not work with Jython 2.5) or hacky (it will break with cryptic JVM stacktrace not really leading to solution).

My preferred way to integrate the two would use RPC. XML RPC is not a bad choice here, if you have moderate amounts of data. It is pretty well supported — Python has it in its standard library. Java libraries are also easy to find. Now depending on your setup either Java or Python part would be a server accepting connection from other language.

A less popular but worth considering alternative way to do RPCs is Google protobuffers, which have 2/3 of support for nice rpc. You just need to provide your transport layer. Not that much work and the convenience of writing is reasonable.

Another option is to write a C wrapper around that pieces of Python functionality that you need to expose to Java and use it via JVM native plugins. You can ease the pain by going with SWIG SWIG.

Essentially in your case it works like that:

  1. Create a SWIG interface for all method calls from Java to C++.
  2. Create C/C++ code that will receive your calls and internally call python interpreter with right params.
  3. Convert response you get from python and send it via swig back to your Java code.

This solution is fairly complex, a bit of an overkill in most cases. Still it is worth doing if you (for some reason) cannot afford RPCs. RPC still would be my preferred choice, though.

🌐
Py4j
py4j.org
Welcome to Py4J — Py4J
Py4J enables Python programs running in a Python interpreter to dynamically access Java objects in a Java Virtual Machine. Methods are called as if the Java objects resided in the Python interpreter and Java collections can be accessed through standard Python collection methods.
🌐
Dirtsimple
dirtsimple.org › 2004 › 12 › python-interfaces-are-not-java.html
Python Interfaces are not Java Interfaces - dirtSimple.org
April 23, 2006 - First of all, in Python, interfaces are much more dynamic than their counterparts in Java. For example, Java doesn’t let you change your mind on the fly about what interface a class or an instance supports, but Python does.
🌐
Devmio
devm.io › python › integrating-python-with-java-170663
Integrating Python with Java
April 21, 2020 - Python is an object-oriented scripting language, which automatically makes it a good pair for Java. But when combined with a Python interpreter written entirely in Java, like Jython, you could do things like write entire applets in Python.
Find elsewhere
🌐
LinkedIn
linkedin.com › pulse › integrating-python-java-guide-developers-myexamcloud-7g5bc
Integrating Python and Java: A Guide for Developers
December 26, 2023 - JPype is a Python module that enables integration with Java code via Java Virtual Machine (JVM). It provides an easy-to-use interface to call Java functions and libraries from within a Python program.
🌐
Net Informations
net-informations.com › python › iq › interfaces.htm
Does Python supports interfaces like in Java or C#?
Python does not have explicit interfaces like Java or C#, but it achieves similar functionality through abstract base classes (ABCs) provided by the abc module. These abstract classes define methods that subclasses are expected to implement, allowing for a form of interface-like behavior while ...
🌐
Tiny PNG
nayuki.io › page › java-native-interface-compared-to-python-c-api
Java Native Interface compared to Python/C API
The Python version shows how to convert between Python’s int objects and native C integer types. The second program, “Create map”, demonstrates how native C code can create a complex graph of Java or Python objects. The Java version looks up existing Java classes and methods, builds strings in C, then invokes the Java methods to create the necessary objects.
🌐
Medium
nicolas1009.medium.com › understanding-polymorphism-and-interfaces-in-python-a-deep-dive-into-duck-typing-and-abstract-1da1dba4e507
“Understanding Polymorphism and Interfaces in Python: A Deep Dive into Duck Typing and Abstract Classes” | by Nicolas Bernal | Medium
October 2, 2023 - Java and C# for example prohibit multiple inheritance. However, they permit a class to implement multiple interfaces, drawing a distinction between “implementation” and “inheritance.” · (Note: Python does allow multiple inheritance, but it’s often best to use composition, aligning more with Python’s philosophy.)
🌐
Chelsea Troy
chelseatroy.com › 2020 › 11 › 14 › why-use-or-not-use-interfaces-in-python
Why use (or not use) interfaces in Python? – Chelsea Troy
November 15, 2020 - The idea of interface adherence isn’t new—in fact, Python provides fewer affordances for it than many other programming languages. Java and Kotlin have the interface keyword. Swift has the protocol keyword.
🌐
Reddit
reddit.com › r/python › python interfaces? what is it for? or it is there because a java developer happens to write python?
r/Python on Reddit: Python interfaces? What is it for? Or it is there because a Java developer happens to write Python?
July 15, 2016 - This gives you nothing that an interface would in Java. Well, Java has types (albeit very very crude ones with blatant holes in the type system), Python doesn't; interfaces are a type system detail, so naturally, applying the concept to an untyped language isn't very meaningful, and I don't believe that's what we're seeing here, although the inspiration is pretty obvious.
🌐
Masnun
masnun.rocks › 2017 › 04 › 15 › interfaces-in-python-protocols-and-abcs
Interfaces in Python: Protocols and ABCs · Abu Ashraf Masnun
April 15, 2017 - There’s no interface keyword in Python. The Java / C# way of using interfaces is not available here. In the dynamic language world, things are more implicit.
🌐
Ptidej Team Blog
blog.ptidej.net › bridging-the-gap-accessing-java-objects-from-python-and-vice-versa
Mind the Gap: Accessing Java Objects from Python and Vice Versa
May 8, 2024 - To exchange custom Python objects with Java, the Python classes should implement Java interfaces. This allows the JVM to call Python objects.
🌐
Jython
jython.org
Home | Jython
import org.python.util.PythonInterpreter; public class JythonHelloWorld { public static void main(String[] args) { try(PythonInterpreter pyInterp = new PythonInterpreter()) { pyInterp.exec("print('Hello Python World!')"); } } } from java.lang import System # Java import print('Running on Java version: ' + System.getProperty('java.version')) print('Unix time from Java: ' + str(System.currentTimeMillis()))
Top answer
1 of 1
1

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.

🌐
DEV Community
dev.to › alvesjessica › interfaces-in-python-not-truly-an-interface-just-a-convention-43d3
Interfaces in Python: not truly an interface, just a convention. - DEV Community
September 14, 2022 - In the Python context, different from strongly typed programming languages such as Java, interface isn’t a thing. There is no interface keyword. But you can try to implement something similar to an interface. In Python we could try to represent an interface creating a kind of specialized class which would be like an abstract class that contains only abstract methods.