← index #6635PR #7623
Related · high · value 0.150
QUERY · ISSUE

real and imag raise exceptions on non-complex numbers

openby HugoNumworksopened 2020-11-19updated 2025-11-06
enhancement

The real or imaginary part of a non-complex number cannot be computed using MicroPython, whereas Python and CPython handle it.
Should I make a PR for this ?
It would be handled with MICROPY_PY_BUILTINS_COMPLEX only.
<img width="603" alt="image" src="https://user-images.githubusercontent.com/67104016/99661222-d0e92000-2a63-11eb-9157-7768d2169e67.png">

CANDIDATE · PULL REQUEST

py/objcomplex: Allow strings of the form -A+Bj.

closedby laurensvalkopened 2021-08-06updated 2022-06-21
py-core

Allows parsing of a complex string with a similar result as CPython.

Until now, only strings like 3j were supported, with strings like 1+2j giving a syntax error.

The following strings will now also work.

print(complex("1+2j"))
print(complex("+1+2j"))
print(complex("-1+2j"))

Cases with only a sign at [0] or no sign at all are treated as they already were.

Checks are added to force A to be real and B to be imaginary. This raises exceptions for the same cases as CPython, like Aj+B, even though MicroPython would otherwise return the correct result.

Fixes this MicroPython forum post.

Edit: Fix commit message < 75 characters per line.

Signed-off-by: Laurens Valk laurens@pybricks.com

Keyboard

j / / n
next pair
k / / p
previous pair
1 / / h
show query pane
2 / / l
show candidate pane
c
copy suggested comment
r
toggle reasoning
g i
go to index
?
show this help
esc
close overlays

press ? or esc to close

copied