[Python-ideas] On evaluating features [was: Unpacking iterables for augmented assignment]

Franklin? Lee leewangzhong+python at gmail.com
Thu Sep 6 14:38:26 EDT 2018


On Thu, Sep 6, 2018 at 2:23 PM Chris Angelico <rosuav at gmail.com> wrote:
>
> On Fri, Sep 7, 2018 at 4:11 AM, Franklin? Lee
> <leewangzhong+python at gmail.com> wrote:
> > On Tue, Aug 28, 2018 at 6:37 PM Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> >>
> >> Guido van Rossum wrote:
> >> > we might propose (as the OP did) that this:
> >> >
> >> >   a, b, c += x, y, z
> >> >
> >> > could be made equivalent to this:
> >> >
> >> >   a += x
> >> >   b += y
> >> >   c += z
> >>
> >> But not without violating the principle that
> >>
> >>     lhs += rhs
> >>
> >> is equivalent to
> >>
> >>     lhs = lhs.__iadd__(lhs)
> >
> > (Corrected: lhs = lhs.__iadd__(rhs))
> >
> > Since lhs here is neither a list nor a tuple, how is it violated? Or
> > rather, how is it any more of a special case than in this syntax:
> >
> >     # Neither name-binding or setitem/setattr.
> >     [a,b,c] = items
> >
> > If lhs is a Numpy array, then:
> >     a_b_c += x, y, z
> > is equivalent to:
> >     a_b_c = a_b_c.__iadd__((x,y,z))
> >
> > We can translate the original example:
> >     a, b, c += x, y, z
> > to:
> >     a, b, c = target_list(a,b,c).__iadd__((x,y,z))
> > where `target_list` is a virtual (not as in "virtual function") type
> > for target list constructs.
>
> What is the virtual type here, and what does its __iadd__ method do? I
> don't understand you here. Can you go into detail? Suppose I'm the
> author of the class that all six of these objects are instances of;
> can I customize the effect of __iadd__ here in some way, and if so,
> how?

I shouldn't have used jargon I had to look up myself.

The following are equivalent and compile down to the same code:
    a, b, c = lst
    [a, b, c] = lst

The left hand side is not an actual list (even though it looks like
one). The brackets are optional. The docs call the left hand side a
target list: https://docs.python.org/3/reference/simple_stmts.html#assignment-statements

"Target list" is not a real type. You can't construct such an object,
or hold one in memory. You can't make a class that emulates it
(without interpreter-specific hacks), because it is a collection of
its names, not a collection of values.

target_list.__iadd__ also does not exist, because target_list does not
exist. However, target_list can be thought of as a virtual type, a
type that the compiler compiles away. We can then consider
target_list.__iadd__ as a virtual operator, which the compiler will
understand but hide from the runtime.

I was making the point that, because the __iadd__ in the example does
not refer to list.__iadd__, but rather a virtual target_list.__iadd__,
there is not yet a violation of the rule.


More information about the Python-ideas mailing list