Cannot overload float()

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
ProudPagan
Posts: 34
Joined: Fri Apr 12, 2019 8:55 am

Cannot overload float()

Post by ProudPagan » Wed May 22, 2019 2:49 am

Hi,

I am redefining int() and float() for my number-like class (simplified floatoverload class below), but I get a TypeError
when trying to use float(). I am returning a floating point number from __float__ ( ).

int( ) works fine.

Any pointers on what might would be much appreciated. I am using:
MicroPython v1.10-278-g673e154df-dirty on 2019-04-16; win32 version

EDIT: This code works with CPython (tried using 3.6.8)

Code: Select all

class floatoverload (object):

	def __init__ (self):
		pass

	def __float__ (self):
		return 99.9

	def __int__ (self):
		return 999
Output:

Code: Select all

>>> from floatoverload import floatoverload
>>> int(floatoverload())
999
>>> float(floatoverload())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't convert floatoverload to float
>>>
Thanks!

User avatar
jimmo
Posts: 553
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia

Re: Cannot overload float()

Post by jimmo » Wed May 22, 2019 2:58 am

Unfortunately__float__ is not implemented in MicroPython. If you're interested in the implementation of __int__ search for MP_UNARY_OP_INT in the repo.

User avatar
pythoncoder
Posts: 3543
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Cannot overload float()

Post by pythoncoder » Wed May 22, 2019 8:28 am

In general subclassing built-in types is not supported by MicroPython. See this doc. A solution which works in some cases is to use composition and to simulate inheritance.
Peter Hinch

Post Reply