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

Justin R. picture Justin R. · Oct 21, 2009 · Viewed 31.9k times · Source

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

Answer

stonemetal picture stonemetal · Oct 21, 2009

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.