← index #11843PR #6148
Off-topic · high · value 0.708
QUERY · ISSUE

docs: non standard behaviour of float()

openby massimosalaopened 2023-06-22updated 2025-11-06
docs

See
https://github.com/micropython/micropython/issues/11735

The official page
https://docs.micropython.org/en/latest/genrst/builtin_types.html#float
should be updated about the different result of

float('_')

(and eventually other invalid inputs)
between Python and MicroPython.

CANDIDATE · PULL REQUEST

Custom float (and complex) casts

closedby nickovsopened 2020-06-14updated 2022-11-15
py-core

This PR implements support for the __float__ and __complex__ special methods as described in the Python data mode for platforms that support the float and complex types. These methods allow custom classes to provide float or complex representations of themselves.

Compatibility with C Python

The exceptions raised by this PR are the same types as those raised by C Python, but the messages are different (shorter, and constant). One minor difference in functionality is that this code raises a TypeError if the type of the results from these methods is not the desired float or complex, whereas C Python 3.6 and 3.7 allow subclasses of those types but issue a deprecation warning to indicate that the strict type will be required in the future.

Is this addition necessary?

The main benefit of this addition is that it improves compatibility with C Python. The two use cases that motivated its creation were (a) custom classes representing sensors that have numeric, non-integer values and (b) allowing better compatibility for a micro-implementation of a subset of NumPy.

The additional code is very small (the static exception messages take up more space than the code on most CPU architectures, and could be made smaller if they were less informative). The code is only present on platforms that already carry the weight of the optional float and complex classes.

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