Skip to content

[Python-Java-Interop] default type conversions #21

@revintec

Description

@revintec
Context context=Context.newBuilder().allowAllAccess(true).build();
Value value=context.eval("python","[\"1\",2,3]");
Object obj=value.as(Object.class);List list=value.as(List.class);
System.out.println(obj.getClass()+": "+((Map)obj).size());
System.out.println(list.getClass()+": "+list.size());

as the code above shown, ["1",2,3] is a Python <class 'list'>
however when converted to Java object, it became a PolyglotMap(with zero size)
instead of Object[] or List

is this behavior intended? if so, is there any way to customize it to return Object[] or List?
when used like this: JavaMap getMap(){...}; Pythondict=getMap();dict.put("key",["1",2,3])
it corrupts the data inside the map values


and another related Java-Python-Interop question:

context.getBindings("python").putMember("getMap",(Supplier<Map>)HashMap::new);
try{context.eval("python","dict=getMap();dict[\"a\"]");}catch(Throwable e){e.printStackTrace();}
try{context.eval("python","dict=getMap();dict[\"a\"]=1");}catch(Throwable e){e.printStackTrace();}

is there a way to convert Java Map to PolyglotMap so we can use it like a dict in Python?
currently I'm recursively wrapping them to ProxyObject, but it's cumbersome and pollutes map values

KeyError: invalid key a
	at <python> <module 'Unnamed'>(Unnamed:1:14-22)
	at org.graalvm.polyglot.Context.eval(Context.java:340)
	at BugReport.main(BugReport.java:21)
AttributeError: JavaObject[{} (java.util.HashMap)] instance has no attribute '__setitem__'
	at <python> <module 'Unnamed'>(Unknown)
	at org.graalvm.polyglot.Context.eval(Context.java:340)
	at BugReport.main(BugReport.java:22)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions