Addition of a .= operator

Chris Angelico rosuav at gmail.com
Tue May 23 17:12:32 EDT 2023


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)

The pipeline is still visible, you've avoided the "user = user ."
replication, and you've ALSO avoided duplicating "user = " on each
line too.

IMO the ".=" syntax would actually be a bit of a nuisance in this
style of code. Consider how it would look, with your original str
constructor in the middle:

    user = request.GET["user"]
    user = str(user, encoding="utf-8")
    user .= strip()
    user .= lower()
    user = orm.user.get(name=user)

The fact that two of them are ".=" rather than "=" is a bit too subtle
for my liking, possibly because the dot is so small.

ChrisA


More information about the Python-list mailing list