Python vs. PHP duck typing
Friday, August 12th, 2011 02:44 pm GMT +2

Having previous experience in writing PHP code could potentially lead you to hours of debugging in Python.
Consider the following simple example in PHP:

PHP


$s = "0";
$my = (bool) $s;

var_dump($s);
var_dump($my)

And the output would be:


string(1) "0"
bool(false)

Which is pretty expectable behavior in PHP, since it first casts string to int, and than to boolean.

Consider the same example in Python:

Python


s = "0"
my = bool(s)
print type(s), s
print type(my), my

And the output would be:



<type 'str'> 0
<type 'bool'> True

We’re not going to debate here wether this is good or bad, but you should be aware such things before they’ll steal hours of your time

To achieve the same behavior as in PHP, you’ll need to add explicit integer typecast:


s = "0"
my = bool(int(s))
print type(s), s
print type(my), my

And the output would be:



<type 'str'> 0
<type 'bool'> False