GraalVM Polyglot API for embedding and executing Python code within Java applications.
—
Value operations provide the universal interface for working with Python objects from Java. The Value class serves as a language-agnostic wrapper that enables type-safe access to Python values, with automatic conversion capabilities and comprehensive object manipulation methods.
Determine the type of Python values for safe conversion and manipulation.
/**
* Checks if the value represents null/None
* @return true if the value is null/None
*/
public boolean isNull();
/**
* Checks if the value represents a number (int, float, complex)
* @return true if the value is a numeric type
*/
public boolean isNumber();
/**
* Checks if the value represents a boolean
* @return true if the value is a boolean
*/
public boolean isBoolean();
/**
* Checks if the value represents a string
* @return true if the value is a string
*/
public boolean isString();
/**
* Checks if the value represents a date object
* @return true if the value is a date
*/
public boolean isDate();
/**
* Checks if the value represents a time object
* @return true if the value is a time
*/
public boolean isTime();
/**
* Checks if the value represents a timezone
* @return true if the value is a timezone
*/
public boolean isTimeZone();
/**
* Checks if the value represents a duration
* @return true if the value is a duration
*/
public boolean isDuration();
/**
* Checks if the value is a Java host object
* @return true if the value is a host object
*/
public boolean isHostObject();
/**
* Checks if the value is a proxy object
* @return true if the value is a proxy
*/
public boolean isProxyObject();
/**
* Checks if the value represents a native pointer
* @return true if the value is a native pointer
*/
public boolean isNativePointer();
/**
* Checks if the value represents an exception
* @return true if the value is an exception
*/
public boolean isException();
/**
* Checks if the value is a meta-object (type/class)
* @return true if the value is a meta-object
*/
public boolean isMetaObject();
/**
* Checks if the value is an iterator
* @return true if the value is an iterator
*/
public boolean isIterator();Usage Examples:
Value pythonValue = context.eval("python", "42");
if (pythonValue.isNumber()) {
int number = pythonValue.asInt();
}
Value pythonList = context.eval("python", "[1, 2, 3]");
if (pythonList.hasArrayElements()) {
long size = pythonList.getArraySize(); // 3
}
Value pythonDict = context.eval("python", "{'name': 'Alice', 'age': 30}");
if (pythonDict.hasMembers()) {
Set<String> keys = pythonDict.getMemberKeys(); // ["name", "age"]
}Convert Python values to Java types with automatic type coercion.
/**
* Converts to Java boolean
* @return boolean representation
* @throws ClassCastException if conversion fails
*/
public boolean asBoolean();
/**
* Converts to Java byte
* @return byte representation
* @throws ClassCastException if conversion fails
*/
public byte asByte();
/**
* Converts to Java short
* @return short representation
* @throws ClassCastException if conversion fails
*/
public short asShort();
/**
* Converts to Java int
* @return int representation
* @throws ClassCastException if conversion fails
*/
public int asInt();
/**
* Converts to Java long
* @return long representation
* @throws ClassCastException if conversion fails
*/
public long asLong();
/**
* Converts to Java BigInteger
* @return BigInteger representation
* @throws ClassCastException if conversion fails
*/
public BigInteger asBigInteger();
/**
* Converts to Java float
* @return float representation
* @throws ClassCastException if conversion fails
*/
public float asFloat();
/**
* Converts to Java double
* @return double representation
* @throws ClassCastException if conversion fails
*/
public double asDouble();
/**
* Converts to Java String
* @return String representation
* @throws ClassCastException if conversion fails
*/
public String asString();
/**
* Converts to original Java host object
* @param <T> the expected type
* @return the original host object
* @throws ClassCastException if not a host object or wrong type
*/
public <T> T asHostObject();
/**
* Converts to specific Java type with type coercion
* @param <T> target type
* @param targetType the target class
* @return converted value
* @throws ClassCastException if conversion fails
*/
public <T> T as(Class<T> targetType);
/**
* Converts using generic type literal for complex types
* @param <T> target type
* @param targetType TypeLiteral describing the target type
* @return converted value
* @throws ClassCastException if conversion fails
*/
public <T> T as(TypeLiteral<T> targetType);Usage Examples:
// Numeric conversions
Value intValue = context.eval("python", "42");
int javaInt = intValue.asInt(); // 42
double javaDouble = intValue.asDouble(); // 42.0
Value floatValue = context.eval("python", "3.14159");
float javaFloat = floatValue.asFloat(); // 3.14159f
// String conversion
Value stringValue = context.eval("python", "'Hello, World!'");
String javaString = stringValue.asString(); // "Hello, World!"
// Boolean conversion
Value boolValue = context.eval("python", "True");
boolean javaBool = boolValue.asBoolean(); // true
// Complex type conversion
Value pythonList = context.eval("python", "[1, 2, 3, 4, 5]");
List<Integer> javaList = pythonList.as(new TypeLiteral<List<Integer>>() {});
// Host object retrieval
context.getPolyglotBindings().putMember("javaObject", new ArrayList<>());
Value hostValue = context.eval("python", "polyglot.import_value('javaObject')");
ArrayList<?> originalList = hostValue.asHostObject();Access and manipulate attributes of Python objects.
/**
* Checks if the value has members (attributes/properties)
* @return true if the value has accessible members
*/
public boolean hasMembers();
/**
* Gets a member by key
* @param key the member name
* @return Value representing the member
* @throws UnsupportedOperationException if no members
*/
public Value getMember(String key);
/**
* Checks if a specific member exists
* @param key the member name
* @return true if the member exists
*/
public boolean hasMember(String key);
/**
* Sets a member value
* @param key the member name
* @param value the value to set
* @throws UnsupportedOperationException if members not writable
*/
public void putMember(String key, Object value);
/**
* Removes a member
* @param key the member name
* @return true if the member was removed
* @throws UnsupportedOperationException if members not removable
*/
public boolean removeMember(String key);
/**
* Gets all member keys
* @return Set of member names
* @throws UnsupportedOperationException if no members
*/
public Set<String> getMemberKeys();Usage Examples:
// Python object attribute access
context.eval("python", """
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hi, I'm {self.name}"
person = Person("Alice", 30)
""");
Value person = context.getBindings("python").getMember("person");
// Get attributes
Value name = person.getMember("name");
String nameStr = name.asString(); // "Alice"
Value age = person.getMember("age");
int ageInt = age.asInt(); // 30
// Call methods
Value greetMethod = person.getMember("greet");
Value greeting = greetMethod.execute();
String greetingStr = greeting.asString(); // "Hi, I'm Alice"
// Set attributes
person.putMember("email", "alice@example.com");
// List all attributes
Set<String> memberKeys = person.getMemberKeys();
// Contains: name, age, greet, email, etc.
// Check attribute existence
boolean hasName = person.hasMember("name"); // true
boolean hasPhone = person.hasMember("phone"); // false
// Dictionary access
Value pythonDict = context.eval("python", "{'x': 10, 'y': 20}");
Value x = pythonDict.getMember("x"); // 10
pythonDict.putMember("z", 30);Work with Python sequences and lists as arrays.
/**
* Checks if the value has array elements
* @return true if the value is array-like
*/
public boolean hasArrayElements();
/**
* Gets an array element by index
* @param index the element index (0-based)
* @return Value representing the element
* @throws UnsupportedOperationException if not array-like
* @throws InvalidArrayIndexException if index invalid
*/
public Value getArrayElement(long index);
/**
* Sets an array element
* @param index the element index
* @param value the value to set
* @throws UnsupportedOperationException if not array-like or not writable
*/
public void setArrayElement(long index, Object value);
/**
* Removes an array element
* @param index the element index
* @return true if the element was removed
* @throws UnsupportedOperationException if not removable
*/
public boolean removeArrayElement(long index);
/**
* Gets the array size
* @return number of array elements
* @throws UnsupportedOperationException if not array-like
*/
public long getArraySize();Usage Examples:
// Python list operations
Value pythonList = context.eval("python", "[10, 20, 30, 40, 50]");
// Check if it's array-like
if (pythonList.hasArrayElements()) {
long size = pythonList.getArraySize(); // 5
// Get elements
Value firstElement = pythonList.getArrayElement(0);
int first = firstElement.asInt(); // 10
Value lastElement = pythonList.getArrayElement(size - 1);
int last = lastElement.asInt(); // 50
// Set elements
pythonList.setArrayElement(2, 999);
// List is now [10, 20, 999, 40, 50]
// Iterate through elements
for (long i = 0; i < size; i++) {
Value element = pythonList.getArrayElement(i);
System.out.println("Element " + i + ": " + element.asString());
}
}
// Tuple operations
Value pythonTuple = context.eval("python", "(1, 'hello', 3.14)");
long tupleSize = pythonTuple.getArraySize(); // 3
Value stringElement = pythonTuple.getArrayElement(1);
String str = stringElement.asString(); // "hello"
// String as character array
Value pythonString = context.eval("python", "'Hello'");
if (pythonString.hasArrayElements()) {
long length = pythonString.getArraySize(); // 5
Value firstChar = pythonString.getArrayElement(0);
String ch = firstChar.asString(); // "H"
}Execute Python functions and callable objects.
/**
* Checks if the value is executable (callable)
* @return true if the value can be executed
*/
public boolean canExecute();
/**
* Executes the callable with arguments
* @param arguments the arguments to pass
* @return Value representing the execution result
* @throws UnsupportedOperationException if not executable
* @throws PolyglotException if execution fails
*/
public Value execute(Object... arguments);
/**
* Checks if the value can be instantiated (is a constructor)
* @return true if the value can create new instances
*/
public boolean canInstantiate();
/**
* Creates a new instance using this value as constructor
* @param arguments the constructor arguments
* @return Value representing the new instance
* @throws UnsupportedOperationException if not instantiable
* @throws PolyglotException if instantiation fails
*/
public Value newInstance(Object... arguments);Usage Examples:
// Python function execution
context.eval("python", """
def add(a, b):
return a + b
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
class Calculator:
def __init__(self, name):
self.name = name
def multiply(self, a, b):
return a * b
""");
Value bindings = context.getBindings("python");
// Execute functions
Value addFunc = bindings.getMember("add");
if (addFunc.canExecute()) {
Value result = addFunc.execute(5, 3);
int sum = result.asInt(); // 8
}
Value greetFunc = bindings.getMember("greet");
Value greeting1 = greetFunc.execute("Alice");
String msg1 = greeting1.asString(); // "Hello, Alice!"
Value greeting2 = greetFunc.execute("Bob", "Hi");
String msg2 = greeting2.asString(); // "Hi, Bob!"
// Class instantiation
Value calculatorClass = bindings.getMember("Calculator");
if (calculatorClass.canInstantiate()) {
Value calculator = calculatorClass.newInstance("MyCalc");
// Call instance methods
Value multiplyMethod = calculator.getMember("multiply");
Value product = multiplyMethod.execute(6, 7);
int result = product.asInt(); // 42
}
// Built-in function execution
Value lenFunc = bindings.getMember("len");
Value listLen = lenFunc.execute(Arrays.asList(1, 2, 3, 4));
int length = listLen.asInt(); // 4
// Lambda execution
Value pythonLambda = context.eval("python", "lambda x: x ** 2");
Value squared = pythonLambda.execute(5);
int result = squared.asInt(); // 25Work with Python iterators and iterables.
/**
* Checks if the value is an iterator
* @return true if the value is an iterator
*/
public boolean isIterator();
/**
* Checks if the value is iterable
* @return true if the value can produce an iterator
*/
public boolean hasIterator();
/**
* Gets an iterator for this iterable value
* @return Value representing the iterator
* @throws UnsupportedOperationException if not iterable
*/
public Value getIterator();
/**
* Checks if the iterator has more elements
* @return true if more elements available
* @throws UnsupportedOperationException if not an iterator
*/
public boolean hasIteratorNextElement();
/**
* Gets the next element from the iterator
* @return Value representing the next element
* @throws UnsupportedOperationException if not an iterator
* @throws NoSuchElementException if no more elements
*/
public Value getIteratorNextElement();Usage Examples:
// Iterate over Python list
Value pythonList = context.eval("python", "[1, 2, 3, 4, 5]");
if (pythonList.hasIterator()) {
Value iterator = pythonList.getIterator();
while (iterator.hasIteratorNextElement()) {
Value element = iterator.getIteratorNextElement();
System.out.println(element.asInt());
}
}
// Iterate over Python generator
context.eval("python", """
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fib_gen = fibonacci()
""");
Value fibGen = context.getBindings("python").getMember("fib_gen");
if (fibGen.hasIterator()) {
Value iterator = fibGen.getIterator();
// Get first 10 Fibonacci numbers
for (int i = 0; i < 10; i++) {
if (iterator.hasIteratorNextElement()) {
Value fibNumber = iterator.getIteratorNextElement();
System.out.println("Fib " + i + ": " + fibNumber.asInt());
}
}
}
// Dictionary iteration
Value pythonDict = context.eval("python", "{'a': 1, 'b': 2, 'c': 3}");
Value dictKeys = pythonDict.getMember("keys").execute();
if (dictKeys.hasIterator()) {
Value keyIterator = dictKeys.getIterator();
while (keyIterator.hasIteratorNextElement()) {
Value key = keyIterator.getIteratorNextElement();
Value value = pythonDict.getMember(key.asString());
System.out.println(key.asString() + " -> " + value.asInt());
}
}/**
* Type literal for specifying generic types in conversions
* @param <T> the generic type
*/
public abstract class TypeLiteral<T> {
/**
* Gets the generic type information
* @return Type representing the generic type
*/
public final Type getType();
/**
* Gets the raw class type
* @return Class representing the raw type
*/
public final Class<T> getRawType();
}
/**
* Exception thrown when array index is invalid
*/
public final class InvalidArrayIndexException extends PolyglotException {
public long getInvalidIndex();
}
/**
* Exception thrown when trying to access members that don't exist
*/
public final class UnsupportedMessageException extends PolyglotException {
public String getUnsupportedMessage();
}Install with Tessl CLI
npx tessl i tessl/maven-org-graalvm-polyglot--python