Search code examples
pythoncastingtypescoercion

What's the difference between casting and coercion in Python?


In the Python documentation and on mailing lists I see that values are sometimes "cast", and sometimes "coerced".


Solution

  • I think "casting" shouldn't be used for Python; there are only type conversion, but no casts (in the C sense). A type conversion is done e.g. through int(o) where the object o is converted into an integer (actually, an integer object is constructed out of o). Coercion happens in the case of binary operations: if you do x+y, and x and y have different types, they are coerced into a single type before performing the operation. In 2.x, a special method __coerce__ allows object to control their coercion.