In the Python documentation and on mailing lists I see that values are sometimes "cast", and sometimes "coerced". What is the difference?
+10
A:
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.
Martin v. Löwis
2009-10-21 16:55:57
A:
Cast is explicit. Coerce is implicit.
In C++:
2.0 + static_cast<double>(1) //cast
1.0 + 2 //coerce
stonemetal
2009-10-21 17:11:03
-1. That's C++ nomenclature; Python uses different terminology.
SamB
2010-07-11 00:39:16