[Python-ideas] Add .= as a method return value assignment operator

Steven D'Aprano steve at pearwood.info
Thu Sep 27 20:03:32 EDT 2018

On Thu, Sep 27, 2018 at 10:44:38PM +0300, Taavi Eomäe wrote:
> > Do you see how this creates an ambiguous situation?
> Name shadowing could create such ambiguous situations anyways even without
> the new operator?

How? Can you give an example?

Normally, there is no way for a bare name to shadow a dotted name, or 
vice versa, since the dotted name always needs to be fully qualified. In 
the example below, we can talk about "text.encode" which is always the 
method, or "encode", which is always the function and never the method.

I agree that this adds ambiguity where we can't be sure whether text .= 
encode('utf-8') is referring to the function or the method. We can infer 
that it *ought* to be the method, and maybe even add a rule to force 
that, but this works only for the simple cases. It is risky and error 
prone in the hard cases.

Think about a more complex assignment:

    text .= encode(spam) + str(eggs)

This could mean any of:

    text.encode(spam) + text.str(eggs)
    text.encode(spam) + str(eggs)
    encode(spam) + text.str(eggs)
    encode(spam) + str(eggs)

In a statically typed language, the compiler could work out what is 
needed at compile-time (it knows that text.str doesn't exist) and either 
resolve any such ambiguities or refuse to compile. But in a dynamic 
language like Python, you can't tell whether text.str exists or not 
until you try it.

So this proposal suffers from the same problems as Pascal-style "with" 
blocks, which are a FAQ:


> > On 2018-09-27 14:13, Calvin Spealman wrote:
> > > Absolutely -1 on this. Consider the following example:
> > >
> > > def encode(s, *args):
> > >      """Force UTF 8 no matter what!"""
> > >      return s.encode('utf8')
> > >
> > > text = "Hello, there!"
> > > text .= encode('latin1')


More information about the Python-ideas mailing list