user2975192
user2975192

Reputation: 327

Why is this a type error and not a syntax error

Why would the code

print("Average =" (sum/count))

produce a type error and not a syntax error, seeing as a comma is missing?

Thanks.

Upvotes: 1

Views: 1232

Answers (3)

Maxime Lorant
Maxime Lorant

Reputation: 36161

The interpreter is seeing the line as a function call, function which has to be "Average =", but it's impossible because str aren't callable. So you get a type error exception.

>>> print("Average =" (sum/count))
 #        ^^^^^^^^^^^  ^^^^^^^^^
 #         fct name        arg1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable

A callable object is a object where its class implemented the __call__ function. It's useful in some case (see the link below), but the str type doesn't implement it (because it has no sense).
More info about callable object: Python __call__ special method practical example

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1122342

Python treats the () as a function call; strings are not callable resulting in a TypeError:

>>> "somestring"(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable

In Python, everything is an object; functions are objects too, any object could implement a __call__ method, making every object potentially callable. Python won't know that the string object is not callable until runtime, so this is not a syntax error.

Upvotes: 6

tckmn
tckmn

Reputation: 59283

That's valid syntax for a function call (what if "Average =" was replaced with a method name?), and you can't call a string.

Upvotes: 0

Related Questions