Skip to content

jvmutils

tuprolog.jvmutils

Bridging Python and the JVM, on which 2P-Kt runs.

2P-Kt is written in Kotlin and runs on the Java Virtual Machine (JVM): the tuprolog package reaches its classes through JPype, which lets Python call JVM methods and pass Python values to them. Importing this module makes JVM objects more Pythonic:

  • every JVM method fooBar gets the snake_case alias foo_bar; a getter getFoo() without arguments becomes the property foo (writable if a setFoo setter exists), and a boolean getter isFoo() becomes the property is_foo (e.g. term.is_atom, struct.args);
  • the repr of JVM objects is their toString();
  • JVM Comparables support <, <=, > and >=; JVM exceptions have a message property;
  • Kotlin sequences and Java streams are Python iterables;
  • Python iterables are accepted wherever JVM code expects a java.lang.Iterable, a Kotlin Sequence, a Kotlin Pair or a Kotlin Triple (strings excepted).

It also re-exports a few JVM types, and offers the functions converting Python values into JVM ones (jlist, jiterable, jmap, ksequence, kpair, kfunction, ...). Most users never need them: the factories of the tuprolog packages convert their arguments themselves.

Examples:

>>> from tuprolog.core import atom, struct
>>> struct("f", "a").args
[a]
>>> atom("a") < atom("b")
True
>>> jmap({"a": 1})
{a=1}
See Also

tuprolog.jvmioutils, for streams, readers and writers.

Arrays module-attribute

Arrays = _jutils.Arrays

Java's java.util.Arrays utility class (e.g. Arrays.asList(items)).

ArrayList module-attribute

ArrayList = _jutils.ArrayList

Java's resizable list, java.util.ArrayList.

Iterator module-attribute

Iterator = _jutils.Iterator

Java's iterator interface, java.util.Iterator (methods hasNext() and next()).

Map module-attribute

Map = _jutils.Map

Java's map interface, java.util.Map (see jmap).

NoSuchElementException module-attribute

NoSuchElementException = _jutils.NoSuchElementException

Java's exception for iterators with no more elements, java.util.NoSuchElementException.

Iterable module-attribute

Iterable = _jlang.Iterable

Java's iterable interface, java.lang.Iterable (see jiterable).

Not to be confused with Python's collections.abc.Iterable.

JavaSystem module-attribute

JavaSystem = _jlang.System

Java's java.lang.System class (e.g. JavaSystem.getProperty("java.version")).

Object module-attribute

Object = _jlang.Object

Java's java.lang.Object, the root of the JVM class hierarchy.

Pair module-attribute

Pair = _kotlin.Pair

Kotlin's pair of values, kotlin.Pair (properties first and second; see kpair).

Triple module-attribute

Triple = _kotlin.Triple

Kotlin's triple of values, kotlin.Triple (properties first, second and third; see ktriple).

Sequence module-attribute

Sequence = _ksequences.Sequence

Kotlin's lazy sequence, kotlin.sequences.Sequence: computes its items on demand.

Kotlin sequences are Python iterables; many 2P-Kt methods return them (see ksequence).

SequencesKt module-attribute

SequencesKt = _ksequences.SequencesKt

Kotlin's static utilities for sequences, kotlin.sequences.SequencesKt (e.g. SequencesKt.toList(sequence)).

PyUtils module-attribute

PyUtils = _tuprolog_utils.PyUtils

2P-Kt's helpers for Python interoperability, it.unibo.tuprolog.utils.PyUtils.

Its iterable(...) wraps JVM iterables and sequences as public JVM objects (see protect_iterable).

protect_iterable

protect_iterable(iterable: Any) -> Any

Wraps a JVM iterable so that Python can call its iterator() method.

JPype hides the interfaces of instances of non-public JVM classes (such as many iterables returned by Kotlin code): wrapping them via PyUtils.iterable exposes them again. Instances of non-public classes which JPype shows as java.lang.Object$Anonymous are returned as they are, as this module makes them Python iterables already.

Parameters:

Name Type Description Default
iterable Any

A JVM Iterable or Kotlin Sequence.

required

Returns:

Type Description
Any

A JVM iterable with the same items, whose iterator() is callable from Python.

kpair

kpair(items: Iterable) -> Pair

Converts two items into a Kotlin Pair.

Parameters:

Name Type Description Default
items Iterable

A Pair, returned as it is, or a Python iterable of exactly two items.

required

Returns:

Type Description
Pair

The pair.

Raises:

Type Description
ValueError

If items does not contain exactly two items.

Examples:

>>> pair = kpair((1, "a"))
>>> pair.first, pair.second
(1, 'a')

ktriple

ktriple(items: Iterable) -> Triple

Converts three items into a Kotlin Triple.

Parameters:

Name Type Description Default
items Iterable

A Triple, returned as it is, or a Python iterable of exactly three items.

required

Returns:

Type Description
Triple

The triple.

Raises:

Type Description
ValueError

If items does not contain exactly three items.

Examples:

>>> ktriple([1, 2, 3]).third
3

jlist

jlist(iterable: Iterable) -> Iterable

Copies the items of a Python iterable into a JVM java.util.List.

Parameters:

Name Type Description Default
iterable Iterable

The items. A Python list is wrapped rather than copied (via Arrays.asList), giving a fixed-size JVM list.

required

Returns:

Type Description
Iterable

The JVM list.

Examples:

>>> jlist(x * x for x in range(3))
[0, 1, 4]

jiterable

jiterable(iterable: Iterable) -> Any

Wraps a Python iterable as a JVM java.lang.Iterable, without copying it.

JVM code may iterate an Iterable more than once: one-shot Python iterators (e.g. generators) are thus buffered, lazily, while being consumed.

Parameters:

Name Type Description Default
iterable Iterable

The items.

required

Returns:

Type Description
Any

A JVM proxy implementing java.lang.Iterable, meant to be passed to JVM methods.

Examples:

>>> iterator = jiterable(x * x for x in range(3)).iterator()
>>> iterator.hasNext(), iterator.next()
(True, 0)

jarray

jarray(type: Any, rank: int = 1) -> Any

The JVM array type with items of type type, and rank dimensions.

Calling the returned type with a Python sequence creates a JVM array.

Examples:

>>> jarray(Object)
<java class 'java.lang.Object[]'>
>>> list(jarray(Object)([None, None]))
[None, None]

jiterator

jiterator(iterator: Iterator) -> Iterator

Wraps a Python iterator as a JVM java.util.Iterator, consuming it lazily.

Examples:

>>> iterator = jiterator(iter([1, 2]))
>>> iterator.next(), iterator.next(), iterator.hasNext()
(1, 2, False)

jmap

jmap(dictionary: Mapping) -> Map

Converts a Python mapping into a JVM java.util.Map.

Examples:

>>> jmap({"a": 1})["a"]
1

ksequence

ksequence(iterable: Iterable) -> Sequence

Wraps a Python iterable as a Kotlin Sequence, consuming it lazily.

The sequence can be iterated only once.

Examples:

>>> list(ksequence(x * x for x in range(3)))
[0, 1, 4]

to_snake_case

to_snake_case(camel_str: str) -> str

Converts a camelCase name into snake_case, as done for the aliases of JVM methods.

Examples:

>>> to_snake_case("getHTTPCode"), to_snake_case("toURI"), to_snake_case("assertA")
('get_http_code', 'to_uri', 'assert_a')

jvm_method

jvm_method(obj: Any, name: str) -> Callable

The JVM method name of obj, even when Python members shadow it.

Customizers and the auto-generated snake_case properties may hide JVM methods having the same name: this finds all the overloads named name declared along the class hierarchy of obj.

Parameters:

Name Type Description Default
obj Any

A JVM object.

required
name str

The name of the JVM method.

required

Returns:

Type Description
Callable

The method bound to obj, trying each overload in turn when called.

Examples:

>>> import java.lang
>>> jvm_method(java.lang.StringBuilder("ab"), "reverse")()
ba

customize_derived

customize_derived(*names: str) -> Callable

Applies some members of a customizer to the classes deriving from the customized one, too.

A class decorator, to be put below @jpype.JImplementationFor. JPype copies the members of a customizer onto the customized class only: a derived class (re)declaring a JVM method with the same name would shadow them. Here the JVM methods are kept as _<name>, as @JOverride does on the customized class itself. As JPype splits overloads among the classes declaring them (e.g. MutableTheory.equals(Object) vs AbstractTheory.equals(Theory, Boolean)), _<name> tries all the JVM methods named name along the MRO.

Parameters:

Name Type Description Default
*names str

The names of the members of the customizer to apply to derived classes.

()

Returns:

Type Description
Callable

The class decorator.

jimplements

jimplements(*interfaces: Any, **kwargs: Any) -> Callable

Makes a Python class implement JVM interfaces, as jpype.JImplements does.

jpype.JImplements replaces the decorated class with a generated subclass, named after it but with no docstring and jpype._jproxy as module: this decorator gives the subclass the docstring, module and qualified name of the decorated class, for help() and documentation tools.

Parameters:

Name Type Description Default
*interfaces Any

The JVM interfaces (classes, or their names).

()
**kwargs Any

The options of jpype.JImplements (e.g. deferred=True).

{}

Returns:

Type Description
Callable

The class decorator.

kfunction

kfunction(arity: int) -> Callable[[Any], Any]

The class wrapping Python callables as Kotlin functions of the given arity.

Kotlin functions (kotlin.jvm.functions.FunctionN) are what 2P-Kt expects wherever it takes callbacks, e.g. the listeners of channels.

Parameters:

Name Type Description Default
arity int

The number of arguments of the functions.

required

Returns:

Type Description
Callable[[Any], Any]

A class whose constructor takes a Python callable with arity arguments, and whose

Callable[[Any], Any]

instances implement kotlin.jvm.functions.Function<arity>.

Examples:

>>> increment = kfunction(1)(lambda x: x + 1)
>>> increment.invoke(1)
2