The Beginner’s Guide To Jython: run Python code inside Java

Konstantin Parakhin
3 min readNov 29, 2021

--

Source: https://www.reddit.com/r/ProgrammerHumor/comments/c2tnnf/python_wrapper_for_java/

Jython is the Java platform implementation of Python which runs on the JVM. Jython is considered as an implementation of Python, but it has almost the same syntax.

Let’s write some code!

Installation

You may check the installation guide provided by developers, but now we’ll use Gradle:

implementation 'org.python:jython-slim:2.7.2'

If you prefer Maven:

<dependency>
<groupId>org.python</groupId>
<artifactId>jython-slim</artifactId>
<version>2.7.2</version>
</dependency>

Basic functionality

First of all, we need to create PythonInterpreter object:

To run Python code, use exec() method:

We may run each type of code. We may create variables and then retrieve them as a PyObject type using get():

Otherwise, we may create a new variable by calling set(String name, Object value). I think this way is more elegant:

Or we may use eval() method which evaluates a string as a Python expression and returns the result.

PyObject type contains:

  • native Python methods (like __call__(...), __str__());
  • methods for converting to common Java types: asInt(), asString(), asDouble(), asLong(), asDouble(). Also there’re useful methods asIterable() and asStringOrNull();
  • invoke() methods to call object method;
  • __tojava__(Class<T> c) method to convert to every Java type;
  • (I may have missed something…)

Let’s play with our created variable. We want to convert it to Java int:

If we want to convert it in String, we may use a good old Integer.toString() method. But we’ll use Jython:

Also, we may use __tojava__() method. Let’s create a Python list and try to cast it to Java List class:

If we only want to iterate over the list, we may use asIterable() method:

Conclusion

Here we’ve played a bit with Jython, looked at some core features.

And we again make sure how wide and interesting programming is 🌎

--

--