Skip to content

Commit f20375e

Browse files
committed
py: Add .real and .imag attributes to complex numbers.
1 parent bb91f11 commit f20375e

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

py/objcomplex.c

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,13 +132,23 @@ STATIC mp_obj_t complex_binary_op(int op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
132132
return mp_obj_complex_binary_op(op, lhs->real, lhs->imag, rhs_in);
133133
}
134134

135+
STATIC void complex_load_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
136+
mp_obj_complex_t *self = self_in;
137+
if (attr == MP_QSTR_real) {
138+
dest[0] = mp_obj_new_float(self->real);
139+
} else if (attr == MP_QSTR_imag) {
140+
dest[0] = mp_obj_new_float(self->imag);
141+
}
142+
}
143+
135144
const mp_obj_type_t mp_type_complex = {
136145
{ &mp_type_type },
137146
.name = MP_QSTR_complex,
138147
.print = complex_print,
139148
.make_new = complex_make_new,
140149
.unary_op = complex_unary_op,
141150
.binary_op = complex_binary_op,
151+
.load_attr = complex_load_attr,
142152
};
143153

144154
mp_obj_t mp_obj_new_complex(mp_float_t real, mp_float_t imag) {

py/qstrdefs.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,11 @@ Q(calcsize)
136136
Q(chr)
137137
Q(classmethod)
138138
Q(_collections)
139+
#if MICROPY_PY_BUILTINS_COMPLEX
139140
Q(complex)
141+
Q(real)
142+
Q(imag)
143+
#endif
140144
Q(dict)
141145
Q(dir)
142146
Q(divmod)

0 commit comments

Comments
 (0)