Class PyObject
- java.lang.Object
-
- java.util.AbstractMap<String,PyObject>
-
- com.chaquo.python.PyObject
-
- All Implemented Interfaces:
AutoCloseable,Map<String,PyObject>
public class PyObject extends AbstractMap<String,PyObject> implements AutoCloseable
Interface to a Python object.
- Python
Noneis represented by Javanull. Other PyObjects can be converted to their Java equivalents usingtoJava(). - 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
PyExceptionon failure.
-
-
Nested Class Summary
-
Nested classes/interfaces inherited from class java.util.AbstractMap
AbstractMap.SimpleEntry<K extends Object,V extends Object>, AbstractMap.SimpleImmutableEntry<K extends Object,V extends Object>
-
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description List<PyObject>asList()Returns a view of the Python object as a list.Map<PyObject,PyObject>asMap()Returns a view of the Python object as a map.Set<PyObject>asSet()Returns a view of the Python object as a set.PyObjectcall(Object... args)Equivalent to Python()syntax.PyObjectcallAttr(String key, Object... args)PyObjectcallAttrThrows(String key, Object... args)Same ascallAttr(), except it directly passes any Java exception thrown by the Python code.PyObjectcallThrows(Object... args)Same ascall(), except it directly passes any Java exception thrown by the Python code.voidclear()Attempts to remove all attributes returned bykeySet().voidclose()Releases the reference to the Python object.booleancontainsKey(Object key)Equivalent to Pythonhasattr().booleancontainsValue(Object o)Returns whether any attribute has the given value.Set<Map.Entry<String,PyObject>>entrySet()See notes onkeySet().booleanequals(Object that)Equivalent to Python==operator.protected voidfinalize()Callsclose().static PyObjectfromJava(Object o)Converts the given Java object to a Python object.PyObjectget(Object key)Equivalent to Pythongetattr().inthashCode()Equivalent to Pythonhash().longid()Equivalent to Pythonid().booleanisEmpty()Equivalent tokeySet().isEmpty().Set<String>keySet()Equivalent to Pythondir().PyObjectput(String key, PyObject value)Equivalent to Pythonsetattr().PyObjectput(String key, Object value)Equivalent to Pythonsetattr().PyObjectremove(Object key)Equivalent to Pythondelattr().Stringrepr()Equivalent to Pythonrepr().booleantoBoolean()Converts a Pythonboolto a Javaboolean.bytetoByte()Converts a Pythonintto a Javabyte.chartoChar()Converts a 1-character Python string to a Javachar.doubletoDouble()Converts a Pythonfloatorintto a Javadouble.floattoFloat()Converts a Pythonfloatorintto a Javafloat.inttoInt()Converts a Pythonintto a Javaint.<T> TtoJava(Class<T> klass)Converts the Python object to the given Java type.longtoLong()Converts a Pythonintto a Javalong.shorttoShort()Converts a Pythonintto a Javashort.StringtoString()Equivalent to Pythonstr().PyObjecttype()Equivalent to Pythontype().-
Methods inherited from class java.util.AbstractMap
clone, putAll, size, values
-
Methods inherited from interface java.util.Map
compute, computeIfAbsent, computeIfPresent, forEach, getOrDefault, merge, putIfAbsent, remove, replace, replace, replaceAll
-
-
-
-
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:
closein interfaceAutoCloseable
-
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
Objectparameters.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
klassis a primitive type such asint, or an immutable value type such asIntegerorString, 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 liketoInt(),toString(), etc.If
klassis 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 iftoJavawas called on it recursively. However, when converting a Pythonbytesorbytearrayobject to a Javabyte[]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
ClassCastExceptionwill be thrown.
-
toBoolean
public boolean toBoolean()
Converts a Pythonboolto a Javaboolean.- Throws:
ClassCastException- if the Python object is not compatible
-
toByte
public byte toByte()
Converts a Pythonintto a Javabyte.- Throws:
ClassCastException- if the Python object is not compatible
-
toChar
public char toChar()
Converts a 1-character Python string to a Javachar.- Throws:
ClassCastException- if the Python object is not compatible
-
toShort
public short toShort()
Converts a Pythonintto a Javashort.- Throws:
ClassCastException- if the Python object is not compatible
-
toInt
public int toInt()
Converts a Pythonintto a Javaint.- Throws:
ClassCastException- if the Python object is not compatible
-
toLong
public long toLong()
Converts a Pythonintto a Javalong.- Throws:
ClassCastException- if the Python object is not compatible
-
toFloat
public float toFloat()
Converts a Pythonfloatorintto a Javafloat.- Throws:
ClassCastException- if the Python object is not compatible
-
toDouble
public double toDouble()
Converts a Pythonfloatorintto a Javadouble.- 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
Mapinterface, but that is for attribute access (Python "." syntax), whereas theMapreturned 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 Pythonid().
-
type
@NotNull public PyObject type()
Equivalent to Pythontype().
-
call
public PyObject call(Object... args)
Equivalent to Python()syntax. Arguments will be converted as described atfromJava(). Keyword arguments can be passed using instances ofKwargat the end of the argument list.
-
callThrows
public PyObject callThrows(Object... args) throws Throwable
Same ascall(), except it directly passes any Java exception thrown by the Python code.- Throws:
Throwable
-
callAttrThrows
public PyObject callAttrThrows(@NotNull String key, Object... args) throws Throwable
Same ascallAttr(), except it directly passes any Java exception thrown by the Python code.- Throws:
Throwable
-
clear
public void clear()
-
isEmpty
public boolean isEmpty()
-
containsKey
public boolean containsKey(@NotNull Object key)Equivalent to Pythonhasattr().- Specified by:
containsKeyin interfaceMap<String,PyObject>- Overrides:
containsKeyin classAbstractMap<String,PyObject>
-
containsValue
public boolean containsValue(Object o)
Returns whether any attribute has the given value. The value will be converted as described atfromJava().- Specified by:
containsValuein interfaceMap<String,PyObject>- Overrides:
containsValuein classAbstractMap<String,PyObject>
-
get
public PyObject get(@NotNull Object key)
Equivalent to Pythongetattr(). In accordance with theMapinterface, when the attribute does not exist, this method returnsnullrather than throwing an exception. To distinguish this from an attribute with a value ofNone, usecontainsKey().
-
put
public PyObject put(@NotNull String key, Object value)
Equivalent to Pythonsetattr(). The value will be converted as described atfromJava().
-
remove
public PyObject remove(@NotNull Object key)
Equivalent to Python
delattr(). This means it can only remove attributes of the object itself, even thoughkeySet()usually includes the object's class attributes as well.In accordance with the
Mapinterface, when the attribute does not exist, this method returnsnullrather than throwing an exception.
-
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
removeoperation), the results of the iteration are undefined. The set supports element removal, but see the notes onremove(). It does not support theaddoraddAlloperations.
-
equals
public boolean equals(Object that)
Equivalent to Python==operator. The given object will be converted as described atfromJava()
-
toString
@NotNull public String toString()
Equivalent to Pythonstr().- Overrides:
toStringin classAbstractMap<String,PyObject>
-
repr
@NotNull public String repr()
Equivalent to Pythonrepr().
-
hashCode
public int hashCode()
Equivalent to Pythonhash().
-
-