Skip to content

Commit f8ba2ec

Browse files
chrysnpfalcon
authored andcommitted
builtin property: accept keyword arguments
this allows python code to use property(lambda:..., doc=...) idiom. named versions for the fget, fset and fdel arguments are left out in the interest of saving space; they are rarely used and easy to enable when actually needed. a test case is included.
1 parent dea585f commit f8ba2ec

3 files changed

Lines changed: 21 additions & 19 deletions

File tree

py/objproperty.c

Lines changed: 13 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -38,28 +38,22 @@ typedef struct _mp_obj_property_t {
3838
} mp_obj_property_t;
3939

4040
STATIC mp_obj_t property_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
41-
mp_arg_check_num(n_args, n_kw, 0, 4, false);
41+
enum { ARG_fget, ARG_fset, ARG_fdel, ARG_doc };
42+
static const mp_arg_t allowed_args[] = {
43+
{ MP_QSTR_, MP_ARG_OBJ, {.u_rom_obj = mp_const_none} },
44+
{ MP_QSTR_, MP_ARG_OBJ, {.u_rom_obj = mp_const_none} },
45+
{ MP_QSTR_, MP_ARG_OBJ, {.u_rom_obj = mp_const_none} },
46+
{ MP_QSTR_doc, MP_ARG_OBJ, {.u_rom_obj = mp_const_none} },
47+
};
48+
mp_arg_val_t vals[MP_ARRAY_SIZE(allowed_args)];
49+
mp_arg_parse_all_kw_array(n_args, n_kw, args, MP_ARRAY_SIZE(allowed_args), allowed_args, vals);
4250

4351
mp_obj_property_t *o = m_new_obj(mp_obj_property_t);
4452
o->base.type = type;
45-
if (n_args >= 4) {
46-
// doc ignored
47-
}
48-
if (n_args >= 3) {
49-
o->proxy[2] = args[2];
50-
} else {
51-
o->proxy[2] = mp_const_none;
52-
}
53-
if (n_args >= 2) {
54-
o->proxy[1] = args[1];
55-
} else {
56-
o->proxy[1] = mp_const_none;
57-
}
58-
if (n_args >= 1) {
59-
o->proxy[0] = args[0];
60-
} else {
61-
o->proxy[0] = mp_const_none;
62-
}
53+
o->proxy[0] = vals[ARG_fget].u_obj;
54+
o->proxy[1] = vals[ARG_fset].u_obj;
55+
o->proxy[2] = vals[ARG_fdel].u_obj;
56+
// vals[ARG_doc] is silently discarded
6357
return MP_OBJ_FROM_PTR(o);
6458
}
6559

py/qstrdefs.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -570,6 +570,7 @@ Q(property)
570570
Q(getter)
571571
Q(setter)
572572
Q(deleter)
573+
Q(doc)
573574
#endif
574575

575576
#if MICROPY_PY_UZLIB

tests/basics/builtin_property.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,3 +93,10 @@ class D:
9393
del d.prop
9494
except AttributeError:
9595
print('AttributeError')
96+
97+
# properties take keyword arguments
98+
class E:
99+
p = property(lambda self: 42, doc="This is truth.")
100+
# not tested for because the other keyword arguments are not accepted
101+
# q = property(fget=lambda self: 21, doc="Half the truth.")
102+
print(E().p)

0 commit comments

Comments
 (0)