Addition of a .= operator

Chris Angelico rosuav at gmail.com
Tue May 23 18:51:19 EDT 2023


On Wed, 24 May 2023 at 08:48, Peter J. Holzer <hjp-python at hjp.at> wrote:
>
> On 2023-05-24 07:12:32 +1000, Chris Angelico wrote:
> > On Wed, 24 May 2023 at 07:04, Peter J. Holzer <hjp-python at hjp.at> wrote:
> > > But I find it easier to read if I just reuse the same variable name:
> > >
> > >     user = request.GET["user"]
> > >     user = str(user, encoding="utf-8")
> > >     user = user.strip()
> > >     user = user.lower()
> > >     user = orm.user.get(name=user)
> > >
> > > Each instance only has a livetime of a single line (or maybe two or
> > > three lines if I have to combine variables), so there's little risk of
> > > confusion, and reusing the variable name makes it very clear that all
> > > those intermediate results are gone and won't be used again.
> > >
> >
> > Small side point: You can make use of the bytes object's decode()
> > method to make the chaining much more useful here, rather than the
> > str() constructor.
> >
> > This sort of code might be better as a single expression. For example:
> >
> > user = (
> >     request.GET["user"]
> >     .decode("utf-8")
> >     .strip()
> >     .lower()
> > )
> > user = orm.user.get(name=user)
>
> Yes, that probably wasn't the best example. I sort of deliberately
> avoided method chaining here to make my point that you don't have to
> invent a new variable name for every intermediate result, but of course
> that backfired because in this case you don't need a variable name at
> all. I should have used regular function calls ...
>

In the context of a .= operator, though, that is *in itself* an
interesting data point: in order to find an example wherein the .=
operator would be plausible, you had to make the .= operator
unnecessary.

ChrisA


More information about the Python-list mailing list