git.net

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Questioning the effects of multiple assignment


On 2020-07-08 12:26:06 +1200, dn via Python-list wrote:
> A matter of style, which I like to follow [is it TDD's influence? - or
> does it actually come-from reading about DBC (Design by Contract*)?]

I think Design by Contract only affects the interfaces (parameters,
return values and side effects), not internal operations of a component.

> is the injunction that one *not* vary the value of a parameter inside
> a method/function.
> (useful in 'open-box testing' to check both the API and that input+process
> agrees with the expected and actual output, but irrelevant for 'closed-box
> testing')
> This also has the effect of side-stepping any unintended issues caused by
> changing the values of mutable parameters!
> (although sometimes it's a equally-good idea to do-so!)
> 
> Accordingly, binding argument-values to mutable parameters (instead of
> an immutable tuple) might cause problems/"side-effects", were those
> parameters' values changed within the function!

I don't think so. The tuple/list is local to the function and never
visible outside of it. So you can change it within the function without
affecting the caller:

#!/usr/bin/python3
def f(*a):
    # a = list(a) # simulate star-as-list
    a.append(2)

v = { "old": 1}
f(v)
print(v)

should print ?{'old': 1}?.

OTOH, using a tuple doesn't prevent the function from mutating mutable
arguments:

#!/usr/bin/python3
def f(*a):
    a[0]["new"] = 2

v = { "old": 1}
f(v)
print(v)

prints ?{'old': 1, 'new': 2}?.

        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: <http://mail.python.org/pipermail/python-list/attachments/20200708/d68e2972/attachment.sig>