[Python-ideas] iterable.__unpack__ method

Alex Stewart foogod at gmail.com
Fri Feb 22 20:33:41 CET 2013


So when putting together my enum implementation I came up against something 
I've run into a couple of times in a few different situations, and I 
thought warranted some discussion as its own proposal:  There are times 
where it would be extremely convenient if there was a way when unpacking an 
object (using the "a, b, c = foo" notation) for that object to know how 
many values it needed to provide.

I would like to propose the following:

When the unpack notation is used, the interpreter will automatically look 
for an __unpack__ method on the rvalue, and if it exists will call it as:

    rvalue.__unpack__(min_count, max_count)

... and use the returned value as the iterable to unpack into the variables 
instead of the original object.  (If no __unpack__ method exists, it will 
just use the rvalue itself, as it does currently)

In the case of simple unpacking ("a, b, c = foo"), min_count and max_count 
will be the same value (3).  In the case of extended unpacking ("a, b, c, 
*d = foo"), min_count would be the smallest length that will not cause an 
unpacking exception (3, in this case), and max_count would be None.

By effectively separating the notion of "unpackable" from "iterable", this 
would allow for a few useful things:

   1. It would allow otherwise non-iterable objects to support the unpack 
   notation if it actually makes sense to do so
   2. It would allow for "smart" unpackable objects (such as __ in my enum 
   example), which would "just work" no matter how many values they're 
   required to produce.
   3. It would allow (properly designed) infinite (or 
   unknown-possibly-large-size) iterators to be unpackable into a finite 
   sequence of variables if desired (which can only be done with extra 
   special-case code currently)
   4. It could make backwards-compatibility easier for APIs which return 
   iterables (i.e. if you want to change a function that used to return a 
   3-tuple to return a 5-tuple, instead of inherently breaking all existing 
   code that chose to unpack the return value (assuming only 3 items would 
   ever be returned), you could return an unpackable object which will work 
   correctly with both old and new code)
   
Thoughts?

--Alex

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130222/12731dd0/attachment.html>


More information about the Python-ideas mailing list