Borislav Hadzhiev
Last updated: Apr 20, 2022
Photo from Unsplash
The Python "TypeError: unsupported operand type(s) for -: 'int' and
'function'" occurs when we try to use the subtraction -
operator with an
integer and a function. To solve the error, make sure to call the function, e.g.
my_func()
.
Here is an example of how the error occurs.
def get_num(): return 25 # ⛔️ TypeError: unsupported operand type(s) for -: 'int' and 'function' result = 50 - get_num
We forgot to invoke the get_num
function so we ended up trying to subtract a
function from an integer.
To solve the error, make sure to call the function.
def get_num(): return 25 # 👇️ use parenthesis to call function result = 50 - get_num() print(result) # 👉️ 25
We used parenthesis to call the function, so we can get its return value.
my_func(10, 20)
.You should be returning a number from the function as trying to subtract different types (e.g. a string and a number) would cause an error.
If you aren't sure what type a variable stores, use the built-in type()
class.
def get_num(): return 25 print(type(get_num)) # 👉️ <class 'function'> print(callable(get_num)) # 👉️ True print(type(get_num())) # 👉 <class 'int'> print(isinstance(get_num(), int)) # 👉️ 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.