float() argument must be string or real number, not method

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

float() argument must be string or real number, not method #

The Python "TypeError: float() argument must be a string or a real number, not 'method'" occurs when we pass a method to the float() class. To solve the error, make sure to call the method with parentheses, e.g. my_method().

float argument must be a string or real number not method

Here is an example of how the error occurs.

main.py
class MyClass(): def get_str(self): return '3.14' m = MyClass() # ⛔️ TypeError: float() argument must be a string or a real number, not 'method' result = float(m.get_str) # 👈️ forgot to call method
We forgot to call the method with parentheses, e.g. m.get_str(), so our code actually tries to convert a method to a floating-point number.

To solve the error, make sure to call the method.

main.py
class MyClass(): def get_str(self): return '3.14' e = MyClass() # ✅ call method() with parentheses result = float(e.get_str()) print(result) # 👉️ 3.14

We used parentheses to invoke the method, so now our code converts the return value of the method to a float.

If your method takes arguments, make sure to provide them when calling it, e.g. my_obj.my_method(10, 20).

If you aren't sure what type of object a variable stores, use the type() class.

main.py
class MyClass(): def get_str(self): return '3.14' e = MyClass() print(type(e.get_str)) # 👉️ <class 'method'> print(callable(e.get_str)) # 👉️ True my_float = 3.14 print(type(my_float)) # 👉️ <class 'float'> print(isinstance(my_float, float)) # 👉️ True

The type class returns the type of an object.

The isinstance function returns True if the passed in object is an instance or a subclass of the passed in class.

The callable function takes an object as an argument and returns True if the object appears callable, otherwise False is returned.

If the callable() function returns True, it is still possible that calling the object fails, however if it returns False, calling the object will never succeed.

Conclusion #

The Python "TypeError: float() argument must be a string or a real number, not 'method'" occurs when we pass a method to the float() class. To solve the error, make sure to call the method with parentheses, e.g. my_method().

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.