Class KeywordArguments

java.lang.Object
org.graalvm.python.embedding.KeywordArguments

public abstract sealed class KeywordArguments extends Object
Represents a set of keyword arguments, typically used for interfacing with Python functions that accept **kwargs.

When to Use

KeywordArguments must be used whenever a Python function accepts named arguments (both required and optional). This ensures proper mapping of Java arguments to Python function parameters, especially when working with Python methods that utilize **kwargs.

Important: An instance of KeywordArguments must always be the last argument when invoking a Python function. It may be preceded by an instance of PositionalArguments, but KeywordArguments must always be the final argument. This ensures proper alignment with Python's argument structure.

The KeywordArguments class provides factory methods to create instances from a Map or by directly specifying key-value pairs.

Usage

Consider the following Python function:

def example_function(*, named1, named2, named3=None, named4=42):
    ...

In this function, named1 and named2 are required keyword arguments, while named3 and named4 are optional because they have default values.

From Java, this function can be invoked as:

value.invokeMember("example_function", kwArgs);

The variable kwArgs can be created in several ways:

Using a map:

KeywordArguments kwargs = KeywordArguments.from(Map.of("named1", 10, "named2", "value", "named4", 100));

Using key-value pairs:

KeywordArguments kwargs = KeywordArguments.of("named1", 10, "named2", "value", "named4", 100);

Using a builder:

public static final class ExampleFunctionKwArgsBuilder {
	private final Map<String, Object> values = new HashMap<>();

	// Constructor includes all required arguments
	public ExampleFunctionKwArgsBuilder(Object named1, Object named2) {
		values.put("named1", named1);
		values.put("named2", named2);
	}

	// Methods for optional arguments
	public ExampleFunctionKwArgsBuilder named3(Object named3) {
		values.put("named3", named3);
		return this;
	}

	public ExampleFunctionKwArgsBuilder named4(Object named4) {
		values.put("named4", named4);
		return this;
	}

	// Add dynamic arguments
	public ExampleFunctionKwArgsBuilder add(String key, Object value) {
		values.put(key, value);
		return this;
	}

	// Build the KeywordArguments instance
	public KeywordArguments build() {
		return KeywordArguments.from(values);
	}
}

Using the builder to create the arguments:

KeywordArguments kwargs = new ExampleFunctionKwArgsBuilder("value1", "value2") // Required keys
		.named4(100) // Optional key
		.add("dynamicKey", 42) // Dynamic key
		.build();
See Also: