Addition of a .= operator

Peter J. Holzer hjp-python at hjp.at
Tue May 23 17:03:26 EDT 2023


On 2023-05-21 20:30:45 +0100, Rob Cliffe via Python-list wrote:
> On 20/05/2023 18:54, Alex Jando wrote:
> > So what I'm suggesting is something like this:
> > 
> > ------------------------------------------------------------
> > hash = hashlib.sha256(b'word')
> > hash.=hexdigest()
> > ------------------------------------------------------------
> > num = Number.One
> > num.=value
> > ------------------------------------------------------------
> It seems to me that this would encourage bad style.  When you write
>     num = num.value
> you are using num with two different meanings (an object and an
> attribute of it).

I think that's ok if it's the same thing at a high level.

I sometimes have a chain of transformations (e.g. first decode it, then
strip extra spaces, then normalize spelling, then look it up in a
database and replace it with the record, ...). Technically, of course
all these intermediate objects are different, and I could make that
explicit by using different variable names:

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

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.

        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/20230523/ec9dd737/attachment.sig>


More information about the Python-list mailing list