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

Fix PyObject call segmentation fault #13

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions src/python.ts
Original file line number Diff line number Diff line change
Expand Up @@ -565,13 +565,25 @@ export class PyObject {
positional: (PythonConvertible | NamedArgument)[] = [],
named: Record<string, PythonConvertible> = {},
) {
const args = py.PyTuple_New(positional.length);
// count named arguments
const namedCount = positional.filter(
(arg) => arg instanceof NamedArgument,
).length;

const positionalCount = positional.length - namedCount;
if (positionalCount < 0) {
throw new PythonError("Not enough arguments");
}

const args = py.PyTuple_New(positionalCount);

let startIndex = 0;
for (let i = 0; i < positional.length; i++) {
const arg = positional[i];
if (arg instanceof NamedArgument) {
named[arg.name] = arg.value;
} else {
py.PyTuple_SetItem(args, i, PyObject.from(arg).owned.handle);
py.PyTuple_SetItem(args, startIndex++, PyObject.from(arg).owned.handle);
}
}
const kwargs = py.PyDict_New();
Expand Down
28 changes: 23 additions & 5 deletions test/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,11 +117,29 @@ class Person:
});
});

Deno.test("named argument", () => {
assertEquals(
python.str("Hello, {name}!").format(new NamedArgument("name", "world"))
.valueOf(),
"Hello, world!",
Deno.test("named argument", async (t) => {
await t.step("single named argument", () => {
assertEquals(
python.str("Hello, {name}!").format(new NamedArgument("name", "world"))
.valueOf(),
"Hello, world!",
);
});

await t.step(
"combination of positional parameters and named argument",
() => {
const { Test } = python.runModule(`
class Test:
def test(self, *args, **kwargs):
return all([len(args) == 3, "name" in kwargs])
`);
const t = new Test();

const d = python.dict({ a: 1, b: 2 });
const v = t.test(1, 2, new NamedArgument("name", "vampire"), d);
assertEquals(v.valueOf(), true);
},
);
});

Expand Down