Skip to content

Commit 52c4b65

Browse files
committed
add new example
1 parent e1808a7 commit 52c4b65

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,10 @@
1+
# my_print(*args, sep=', ')
12
my_print(1, '2', 3.0, True, [None, ('a', 'b')])
23

34
a = [i for i in range(5)]
45
my_print(*a, sep=' | ')
6+
7+
8+
# my_print_kw(sep='=', **kwargs)
9+
my_print_kw(a=1, b='2', c=3.0, d=True)
10+
my_print_kw(a=1, b='2', c=3.0, d=True, sep=': ')

examples/06 Bind Variadic Function/main.c

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,32 @@ static bool my_print(int argc, py_Ref argv) {
2525
return true;
2626
}
2727

28+
static bool my_print_kw_dict_apply(py_Ref key, py_Ref value, void *ctx) {
29+
const char *sep = (const char *)ctx;
30+
if (!py_str(key)) return false;
31+
printf("%s=", py_tostr(key));
32+
if (!py_str(value)) return false;
33+
printf("%s%s\n", sep, py_tostr(value));
34+
return true;
35+
}
36+
37+
static bool my_print_kw(int argc, py_Ref argv) {
38+
PY_CHECK_ARGC(2);
39+
PY_CHECK_ARG_TYPE(0, tp_str);
40+
PY_CHECK_ARG_TYPE(1, tp_dict);
41+
const char *sep = py_tostr(py_arg(0));
42+
bool ok = py_dict_apply(py_arg(1), my_print_kw_dict_apply, (void *)sep);
43+
if (!ok) return false;
44+
py_newnone(py_retval());
45+
return true;
46+
}
47+
2848
int main() {
2949
py_initialize();
3050

3151
py_GlobalRef __main__ = py_getmodule("__main__");
3252
py_bind(__main__, "my_print(*args, sep=', ')", my_print);
53+
py_bind(__main__, "my_print_kw(sep='=', **kwargs)", my_print_kw);
3354

3455
if (!py_exec(INPUT, "main.py", EXEC_MODE, NULL)) {
3556
py_printexc();

0 commit comments

Comments
 (0)