Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Java equivalent to Python containers #30

Closed
MustafaHalimehHH opened this issue Jan 26, 2018 · 2 comments
Closed

Java equivalent to Python containers #30

MustafaHalimehHH opened this issue Jan 26, 2018 · 2 comments

Comments

@MustafaHalimehHH
Copy link

Hi,
I am trying to parse a return dict type from python in java, and I tried different things in chaquopy to get the equivalent for dict object but all of them failed.
pyobject.keySet(): returns different keys (I thing the data members of the dict class).
Also the dict contains different types like ({name='name', age='25', boss='False'}), I did not find any code sample to how use the dict in the demo source code.
So how I can use the dict Python object in java.
Thanks.

@mhsmith mhsmith changed the title Java equivalent to Python dict Java equivalent to Python containers Jan 26, 2018
@mhsmith
Copy link
Member

mhsmith commented Jan 26, 2018

You should be able to use the dict by calling its Python methods using callAttr. For example:

PyObject d = /* something returning the dict described above */;
String name = d.callAttr("get", "name").toString();
int age = d.callAttr("get", "age").toJava(int.class);

Or to iterate through the dict:

PyObject keys = py.getBuiltins().callAttr("list", d.callAttr("keys"));
int len = keys.callAttr("__len__").toJava(int.class);
for (int i = 0; i < len; i++) {
    String key = keys.callAttr("__getitem__", i).toString();
    String value = d.callAttr("get", key).toString(); // or .toJava(...)
}

Of course it would be much easier if we could access Python containers through the corresponding Java interfaces. We may implement that in the future, so let's leave this issue open to track it.

@mhsmith
Copy link
Member

mhsmith commented Jan 19, 2019

Chaquopy 5.1.2 adds the following methods to PyObject:

  • asList
  • asMap
  • asSet

@mhsmith mhsmith closed this as completed Jan 19, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants