Pythonification of the asterisk-based collection packing/unpacking syntax

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Dec 18 03:46:57 EST 2011


On Sat, 17 Dec 2011 21:03:01 -0600, Evan Driscoll wrote:

> Something like ML or Haskell, which does not even allow integer to
> double promotions, is very strong typing. Something like Java, which
> allows some arithmetic conversion and also automatic stringification (a
> la "1" + 1) is somewhere in the middle of the spectrum. Personally I'd
> put Python even weaker on account of things such as '[1,2]*2' and '1 <
> True' being allowed,

They are not examples of weak typing. The first is an example of operator 
overloading, the second is a side-effect of a compromise made for 
backwards compatibility.

If the first example were written:

[1, 2].repeat(2)

I expect you'd be perfectly happy with it as an unexceptional example of 
a list method: it takes an integer count, and returns a new list 
consisting of the elements of the original list repeated twice.

If it were written:

[1, 2].__mul__(2)

you'd probably raise an eyebrow at the ugliness of the method name, but 
you would be okay with the concept.

Well, that's exactly what it is in Python: the list __mul__ method 
performs sequence multiplication (repeating the contents), which 
overloads the * operator. No automatic type conversions needed, so not an 
example of weak typing.


As for comparisons between ints and True or False, that's not weak typing 
either, because True and False *are* ints: bool is a subclass of int. 
This was done purely for historical reasons: originally Python didn't 
have a bool type, and you used 0 and 1 by convention for boolean values. 
When it was decided to add a bool type, the least disruptive way to do 
this was to define it as a subclass of int.


-- 
Steven



More information about the Python-list mailing list