Python Glossary Русский

all Python 3Exceptionsexception

TypeError

built-in exceptions

Raised by an operation or a function applied to an object of an unsuitable type. A common case: adding a str to an int.

Syntax

raise TypeError('сообщение')

Keep the line between this and ValueError clear: TypeError means the type is wrong (len(42)), ValueError means the type is right but the value is not usable (int('abc')). The most common source in student code is a None that sneaked in: a function that forgot to return, or a variable holding the result of list.sort()/append() that is later indexed. Calling a function with the wrong number of arguments raises TypeError too, not some separate exception.

Examples

'2' + 2              # TypeError
len(42)              # TypeError
def add(a, b):
    return a + b
add(1, '2')          # TypeError

See also

Open in the full glossarydocs.python.orgReport an inaccuracy