Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 915
Justin R. Avatar asked Oct 21 '09 16:10

Justin R.


People also ask

What is the difference between Type Casting and type coercion in Python?

In type casting, casting operator is needed in order to cast the a data type to another data type. Whereas in type conversion, there is no need for a casting operator. 4. In typing casting, the destination data type may be smaller than the source data type, when converting the data type to another data type.

What is coercion in Python?

Coercion is the implicit conversion of an instance of one type to another during an operation which involves two arguments of the same type.

What does casting mean in Python?

Prerequisites: Python Data Types. Type Casting is the method to convert the variable data type into a certain data type in order to the operation required to be performed by users.

Is there type coercion in Python?

Many programming languages have something called type coercion; it's where the language will implicitly convert one object to another type of object in certain circumstances. Python does not have type coercion.


2 Answers

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.

like image 164
stonemetal Avatar answered Sep 21 '22 20:09

stonemetal


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.

like image 32
Martin v. Löwis Avatar answered Sep 20 '22 20:09

Martin v. Löwis