Class PyObject

  • All Implemented Interfaces:
    AutoCloseable, Map<String,​PyObject>

    public class PyObject
    extends AbstractMap<String,​PyObject>
    implements AutoCloseable

    Interface to a Python object.

    • Python None is represented by Java null. Other PyObjects can be converted to their Java equivalents using toJava().
    • If a Python object is retrieved for which a PyObject already exists, the same PyObject will be returned.

    Unless otherwise specified, all methods in this class throw PyException on failure.

    • Method Detail

      • close

        public void close()

        Releases the reference to the Python object. Unless the object represents an expensive resource, there's no need to call this method: it will be called automatically when the PyObject is garbage-collected.

        After calling close, the PyObject can no longer be used. If there are no other references to the underlying object, it may be destroyed by Python. If it continues to exist and is retrieved by Java code again, a new PyObject will be returned.

        Caution: any references to the same Python object elsewhere in your program will be represented by the same PyObject, so they will all be invalidated by this call.

        Specified by:
        close in interface AutoCloseable
      • fromJava

        public static PyObject fromJava​(Object o)

        Converts the given Java object to a Python object. There's usually no need to call this method: it will be called automatically by the methods of this class which take Object parameters.

        For details of how Java objects are represented in Python, see the Python API.

      • toJava

        @NotNull
        public <T> T toJava​(@NotNull
                            Class<T> klass)

        Converts the Python object to the given Java type.

        If klass is a primitive type such as int, or an immutable value type such as Integer or String, and the Python object is compatible with it, an equivalent Java object will be returned. However, it's more efficient to use the specific methods like toInt(), toString(), etc.

        If klass is an array type, and the Python object is a sequence, then a copy of the sequence will be returned as a new array. In general, each element will be converted as if toJava was called on it recursively. However, when converting a Python bytes or bytearray object to a Java byte[] array, there is an unsigned-to-signed conversion: Python values 128 to 255 will be mapped to Java values -128 to -1.

        If the Python object is a jclass or jarray object which is compatible with klass, the underlying Java object will be returned.

        Otherwise, a ClassCastException will be thrown.

      • toBoolean

        public boolean toBoolean()
        Converts a Python bool to a Java boolean.
        Throws:
        ClassCastException - if the Python object is not compatible
      • toByte

        public byte toByte()
        Converts a Python int to a Java byte.
        Throws:
        ClassCastException - if the Python object is not compatible
      • toChar

        public char toChar()
        Converts a 1-character Python string to a Java char.
        Throws:
        ClassCastException - if the Python object is not compatible
      • toShort

        public short toShort()
        Converts a Python int to a Java short.
        Throws:
        ClassCastException - if the Python object is not compatible
      • toInt

        public int toInt()
        Converts a Python int to a Java int.
        Throws:
        ClassCastException - if the Python object is not compatible
      • toLong

        public long toLong()
        Converts a Python int to a Java long.
        Throws:
        ClassCastException - if the Python object is not compatible
      • toFloat

        public float toFloat()
        Converts a Python float or int to a Java float.
        Throws:
        ClassCastException - if the Python object is not compatible
      • toDouble

        public double toDouble()
        Converts a Python float or int to a Java double.
        Throws:
        ClassCastException - if the Python object is not compatible
      • asList

        @NotNull
        public List<PyObject> asList()

        Returns a view of the Python object as a list. The view is backed by the object, so changes to the object are reflected in the view, and vice-versa.

        To add Java objects to the Python container through the view, first convert them using fromJava().

        Throws:
        UnsupportedOperationException - if the Python object does not implement the methods __getitem__ and __len__.
      • asMap

        @NotNull
        public Map<PyObject,​PyObject> asMap()

        Returns a view of the Python object as a map. The view is backed by the object, so changes to the object are reflected in the view, and vice-versa.

        PyObject already implements the Map interface, but that is for attribute access (Python "." syntax), whereas the Map returned by this method is for container access (Python "[]" syntax).

        To add Java objects to the Python container through the view, first convert them using fromJava().

        Throws:
        UnsupportedOperationException - if the Python object does not implement the methods __contains__, __getitem__, __iter__ and __len__.
      • asSet

        @NotNull
        public Set<PyObject> asSet()

        Returns a view of the Python object as a set. The view is backed by the object, so changes to the object are reflected in the view, and vice-versa.

        To add Java objects to the Python container through the view, first convert them using fromJava().

        Throws:
        UnsupportedOperationException - if the Python object does not implement the methods __contains__, __iter__ and __len__.
      • id

        public long id()
        Equivalent to Python id().
      • type

        @NotNull
        public PyObject type()
        Equivalent to Python type().
      • call

        public PyObject call​(Object... args)
        Equivalent to Python () syntax. Arguments will be converted as described at fromJava(). Keyword arguments can be passed using instances of Kwarg at the end of the argument list.
      • isEmpty

        public boolean isEmpty()
        Equivalent to keySet().isEmpty(). Because keySet usually includes the object's class attributes, isEmpty will never return true even after calling clear(), unless the object has a custom __dir__ method.
        Specified by:
        isEmpty in interface Map<String,​PyObject>
        Overrides:
        isEmpty in class AbstractMap<String,​PyObject>
      • get

        public PyObject get​(@NotNull
                            Object key)
        Equivalent to Python getattr(). In accordance with the Map interface, when the attribute does not exist, this method returns null rather than throwing an exception. To distinguish this from an attribute with a value of None, use containsKey().
        Specified by:
        get in interface Map<String,​PyObject>
        Overrides:
        get in class AbstractMap<String,​PyObject>
      • put

        public PyObject put​(@NotNull
                            String key,
                            Object value)
        Equivalent to Python setattr(). The value will be converted as described at fromJava().
      • remove

        public PyObject remove​(@NotNull
                               Object key)

        Equivalent to Python delattr(). This means it can only remove attributes of the object itself, even though keySet() usually includes the object's class attributes as well.

        In accordance with the Map interface, when the attribute does not exist, this method returns null rather than throwing an exception.

        Specified by:
        remove in interface Map<String,​PyObject>
        Overrides:
        remove in class AbstractMap<String,​PyObject>
      • keySet

        @NotNull
        public Set<String> keySet()

        Equivalent to Python dir(). Unless the object has a custom __dir__ method, this means the result will include attributes from the object's class as well as the object itself.

        The returned set is backed by the Python object, so changes to the object are reflected in the set, and vice-versa. If the object is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The set supports element removal, but see the notes on remove(). It does not support the add or addAll operations.

        Specified by:
        keySet in interface Map<String,​PyObject>
        Overrides:
        keySet in class AbstractMap<String,​PyObject>
      • repr

        @NotNull
        public String repr()
        Equivalent to Python repr().