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

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


Cast is explicit. Coerce is implicit.

The examples in Python would be:

cast(2, POINTER(c_float)) #cast1.0 + 2  #coerce 1.0 + float(2) #conversion

Cast really only comes up in the C FFI. What is typically called casting in C or Java is referred to as conversion in python, though it often gets referred to as casting because of its similarities to those other languages. In pretty much every language that I have experience with (including python) Coercion is implicit type changing.


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.