Addition of a .= operator

Peter J. Holzer hjp-python at hjp.at
Tue May 23 18:46:38 EDT 2023


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 ...

        hp


-- 
   _  | Peter J. Holzer    | Story must make more sense than reality.
|_|_) |                    |
| |   | hjp at hjp.at         |    -- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |       challenge!"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://mail.python.org/pipermail/python-list/attachments/20230524/035475b2/attachment.sig>


More information about the Python-list mailing list