Skillversitas

Modules

A module is a Python file whose contents (functions, classes, variables) can be imported elsewhere. Jython uses the same import system, with one extension: it can also import Java packages as modules, so the line between "Python module" and "Java library" disappears.

Creating a Module

# mymath.py
def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a
import mymath
print(mymath.is_prime(97))   # True
print(mymath.gcd(48, 36))    # 12

from mymath import is_prime
print(is_prime(90))          # False

import mymath as m
print(m.is_prime(2))         # True

The Python Standard Library

import os, sys, json, math
from collections import Counter
from datetime import datetime

print(math.pi)
print(Counter("abracadabra").most_common(2))
print(datetime.now())

Most of the pure-Python standard library works in Jython. C extension modules (the C-accelerated parts of some stdlib modules and third-party C packages) do not, since there is no C ABI on the JVM.

Importing Java Packages

import java.util
import java.io
import java.lang

print(java.util.Arrays.asList(1, 2, 3))
print(java.lang.Math.PI)
print(java.io.File("x.txt").exists())

Java packages follow the same import syntax: import java.util gives you the package, and its classes are attributes. You can also import specific classes: from java.util import HashMap.

The Classpath Matters

jython -cp "libs/mylib.jar" script.py
# or set PYTHONPATH for Python modules; the JVM classpath for Java jars

Java jars must be on the classpath for their packages to be importable. Pass jars with -cp when launching jython.

Module Patterns

  • Put reusable logic in modules; expose a small public API (functions without leading underscores).
  • Use if __name__ == "__main__": blocks for runnable demos inside a module.
  • Keep Java imports at the top of the file so dependencies are visible.

Summary

Jython modules work like Python modules (import, from ... import, as aliases, __main__ demos), the pure-Python standard library is available, and - uniquely - Java packages are importable too (import java.util), provided the jars are on the classpath. This dual module world is the core of Jython's value: one import statement for either ecosystem.