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

Question:

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

Asked By: Justin R.

||

Answers:

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.

Answered By: Martin v. Löwis

Cast is explicit. Coerce is implicit.

The examples in Python would be:

cast(2, POINTER(c_float)) #cast
1.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.

Answered By: stonemetal
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.