Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Support passing hashes to Python
  • Loading branch information
niner committed Oct 14, 2014
1 parent 46c420b commit efc8caa
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
14 changes: 14 additions & 0 deletions lib/Inline/Python.pm6
Expand Up @@ -79,6 +79,12 @@ sub py_list_new(Int)
sub py_list_set_item(OpaquePointer, Int, OpaquePointer)
{ ... }
native(&py_list_set_item);
sub py_dict_new()
returns OpaquePointer { ... }
native(&py_dict_new);
sub py_dict_set_item(OpaquePointer, OpaquePointer, OpaquePointer)
{ ... }
native(&py_dict_set_item);
sub py_call_function(Str, Str, int, CArray[OpaquePointer])
returns OpaquePointer { ... }
native(&py_call_function);
Expand Down Expand Up @@ -177,6 +183,14 @@ multi method p6_to_py(Positional:D $value) returns OpaquePointer {
return $array;
}

multi method p6_to_py(Hash:D $value) returns OpaquePointer {
my $dict = py_dict_new();
for %$value -> $item {
py_dict_set_item($dict, self.p6_to_py($item.key), self.p6_to_py($item.value));
}
return $dict;
}

method !setup_arguments(@args) {
my $len = @args.elems;
my $tuple = py_tuple_new($len);
Expand Down
8 changes: 8 additions & 0 deletions pyhelper.c
Expand Up @@ -137,6 +137,14 @@ void py_list_set_item(PyObject *list, int i, PyObject *item) {
PyList_SetItem(list, i, item);
}

PyObject *py_dict_new() {
return PyDict_New();
}

void py_dict_set_item(PyObject *dict, PyObject *key, PyObject *item) {
PyDict_SetItem(dict, key, item);
}

void py_dec_ref(PyObject *obj) {
Py_DECREF(obj);
}
Expand Down
6 changes: 3 additions & 3 deletions t/p6_to_py.t
Expand Up @@ -4,7 +4,7 @@ use v6;
use Test;
use Inline::Python;

plan 9;
plan 10;

my $py = Inline::Python.new();
$py.run(q[
Expand All @@ -14,8 +14,8 @@ def identity(a):

class Foo {
}
# , { a => 1, b => 2}, Any, Foo.new
for ('abcö', Buf.new('äbc'.encode('latin-1')), 24, 2.4.Num, [1, 2]) -> $obj {
# , Any, Foo.new
for ('abcö', Buf.new('äbc'.encode('latin-1')), 24, 2.4.Num, [1, 2], { a => 1, b => 2}) -> $obj {
is_deeply $py.call('__main__', 'identity', $obj), $obj, "Can round-trip " ~ $obj.^name;
}

Expand Down

0 comments on commit efc8caa

Please sign in to comment.