Page 2 of 2

Re: Calling a python function from C

Posted: Sun Mar 04, 2018 9:29 am
by stijn
lists in python can be created from any iterable, and list is an iterable itself. In other words: use the constructor functionality to copy a list just like you would in Python, i.e. use mp_obj_new_list or whatever it's called. Likely that is exactly what list_copy does as well, didn't check.

Re: Calling a python function from C

Posted: Sun Mar 04, 2018 7:16 pm
by jickster
stijn wrote:
Sun Mar 04, 2018 9:29 am
lists in python can be created from any iterable, and list is an iterable itself. In other words: use the constructor functionality to copy a list just like you would in Python, i.e. use mp_obj_new_list or whatever it's called. Likely that is exactly what list_copy does as well, didn't check.
I'd have to do

Code: Select all

mp_type_list.make_new(NULL, 1, 0, &my_list);
The first 3 args are still superfluous

Re: Calling a python function from C

Posted: Sun Mar 04, 2018 8:19 pm
by stijn
You sure? I'm 99% sure you could do something like my_list_copy = mp_obj_new_list(my_list->len, my_list->items);

Re: Calling a python function from C

Posted: Sun Mar 04, 2018 8:21 pm
by jickster
stijn wrote:
Sun Mar 04, 2018 8:19 pm
You sure? I don't have time to check but I'm 99% sure you could do something like my_list_copy = mp_obj_new_list(my_list->len, my_list->items);
It doesn't make a copy of the items. So if you use this function, the "items" will be shared between the two lists.

Code: Select all

mp_obj_t mp_obj_new_list(size_t n, mp_obj_t *items) {
    mp_obj_list_t *o = list_new(n);
    if (items != NULL) {
        for (size_t i = 0; i < n; i++) {
            o->items[i] = items[i];
        }
    }
    return MP_OBJ_FROM_PTR(o);
}
This actually reveals the utility of adding "mp_obj_make_new(mp_obj_t)" to make a copy of any mp_obj_t

Re: Calling a python function from C

Posted: Mon Mar 05, 2018 9:03 am
by stijn
What you want is called 'deepcopy'. Which is also exactly what the functionality is called in CPython. In general I'd say it's better to avoid that all together though, if you can. Maybe you should rethink your design. Having an attr function which makes deepcopies doesn't follow the 'principle of least surprise' at all.