35

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

Piper
  • 1,266
  • 3
  • 15
  • 26
Justin R.
  • 23,435
  • 23
  • 108
  • 157

2 Answers2

44

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.

stonemetal
  • 6,111
  • 23
  • 25
  • 2
    -1. That's C++ nomenclature; Python uses different terminology. – SamB Jul 11 '10 at 00:39
  • 12
    +1: For this question, the example is perfectly valid. And it's clearly marked as C++. – user183037 May 07 '11 at 21:03
  • 2
    The question is about the term 'cast' in the context of the Python language. The answer which explains that `float(1)` is construction, not casting, is better. – Carl G Dec 31 '13 at 06:33
  • @CarlG It is an odd question, in the context of python cast doesn't really come up. The only place it is mentioned in the documentation is in the C interface where it refers to casts in C and ctypes where it refers to the ctypes.cast function. The other answer is wrong about construction [float()](http://docs.python.org/2/library/functions.html?highlight=float#float) Is clearly called conversion, not construction. Construction is never mentioned in the documentation for any of the built in conversion functions. – stonemetal Jan 06 '14 at 15:43
32

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
  • 124,830
  • 17
  • 198
  • 235