Pythonification of the asterisk-based collection packing/unpacking syntax

Chris Angelico rosuav at gmail.com
Sun Dec 25 11:23:06 EST 2011


On Mon, Dec 26, 2011 at 2:38 AM, Eelco <hoogendoorn.eelco at gmail.com> wrote:
> Until that time, im going
> to ask you to take 'type constraint' by its literal meaning; a
> coercion of the type of a symbol, rather than whatever particular
> meaning it has acquired for you (it might help if you explained that).
> Im not sure if it was you that brought that up, but let me reiterate
> that I dont mean a 'type cast', which is a runtime concept. A 'type
> constraint' is purely a linguistic construct that will be 'compiled
> out')

The dictionary definition of constraint is "a limitation or
restriction", and you're right that it can be "compiled out". In fact,
that is probably the best definition. Assuming everything is written
correctly, you should be able to eliminate all constraints and the
code will still function correctly*; but having the constrains means
that certain illegal operations will throw errors.

Here's two examples of tuple unpacking, one with a type constraint,
the other without:

a, b = ('hello', [1,2,3] )
a, b::list = ('hello', [1,2,3] )

The constraint on the second line means that, if the second element is
not a list, the interpreter should throw an error. It does NOT mean to
completely change the meaning of the statement to _make_ the last
argument into a list. That is not the job of a constraint.

ChrisA

* In databasing, it's not uncommon to have code depend on error
responses for correct operation; for instance, one implementation of
UPSERT is to attempt an INSERT, and if it fails due to a unique key
constraint, do the UPDATE instead. The same is also done in Python -
eg using an exception to terminate a loop - but in the context of this
discussion, assume that errors indicate errors.



More information about the Python-list mailing list