why does .make_new take as arg mp_obj_type_t *type?

C programming, build, interpreter/VM.
Target audience: MicroPython Developers.
Post Reply
jickster
Posts: 197
Joined: Thu Sep 07, 2017 8:57 pm

why does .make_new take as arg mp_obj_type_t *type?

Post by jickster » Sat May 12, 2018 5:47 pm

Is this for inheritance?

Code: Select all

STATIC mp_obj_t type_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
    // instantiate an instance of a class

    mp_obj_type_t *self = MP_OBJ_TO_PTR(self_in);

    if (self->make_new == NULL) {
        if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
            mp_raise_TypeError("cannot create instance");
        } else {
            nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
                "cannot create '%q' instances", self->name));
        }
    }

    // make new instance
    mp_obj_t o = self->make_new(self, n_args, n_kw, args);

    // return new instance
    return o;
}
Please give an example how/when you'd use that arg in a "make_new" function.

All examples I can find don't use that arg like "list_make_new"

Code: Select all

STATIC mp_obj_t list_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
    (void)type_in;
    mp_arg_check_num(n_args, n_kw, 0, 1, false);

    switch (n_args) {
        case 0:
            // return a new, empty list
            return mp_obj_new_list(0, NULL);

        case 1:
        default: {
            // make list from iterable
            // TODO: optimize list/tuple
            mp_obj_t list = mp_obj_new_list(0, NULL);
            return list_extend_from_iter(list, args[0]);
        }
    }
}

stijn
Posts: 228
Joined: Thu Apr 24, 2014 9:13 am

Re: why does .make_new take as arg mp_obj_type_t *type?

Post by stijn » Sat May 12, 2018 6:04 pm

It's to let the C code know what type is being made upon __init__ etc. So yes inheritance comes to mind, and reusing make_new implementations, possibly other things. Search the whole codebase for 'make_new' and you'll find a bunch of usages, see e.g. dict_make_new, set_make_new, mp_obj_exception_make_new, ...

Post Reply