0

Example:

x=y=z=True

I'm wondering if is bad performance-wise due memory or smth since bool for example is immutable.

SakuraFreak
  • 311
  • 1
  • 11
  • 3
    What does `bool` being immutable have to do with performance? – ForceBru Apr 22 '19 at 18:53
  • like if I ask for X will It read {X=Y->Z->True} or {X=True} – SakuraFreak Apr 22 '19 at 18:58
  • 1
    Assignment of immutable values copies them, or at least behaves as if they were copied (caches may be involved). So, your code'll behave as if these three variables refer to copies of `True`. – ForceBru Apr 22 '19 at 19:02
  • Possible duplicate of [Python assigning multiple variables to same value? list behavior](https://stackoverflow.com/questions/16348815/python-assigning-multiple-variables-to-same-value-list-behavior) – MyNameIsCaleb Apr 22 '19 at 19:03
  • Like @ForceBru said, it's fine, they will act independent of each other as copies, but in general it isn't a way that most people format Python code and could bring problems in the future with different object types, such as lists or other mutable types. – MyNameIsCaleb Apr 22 '19 at 19:05
  • This works and will not impact performance. as for code clarity and aesthetic, probably not the best idea. – Rocky Li Apr 22 '19 at 19:09
  • @ForceBru no, it does not. Assignment in Python **never copies**, not even if the object is immutable. The semantics of assignment don't depend on the type of the object. Immutable objects simply lack mutator methods. – juanpa.arrivillaga Apr 22 '19 at 20:52

1 Answers1

2

With single names, it has exactly the same semantics as

x=True
y=x
z=x

but (depending on the “optimization” in the compiler) might be more efficient because it doesn’t (naïvely) involve reloading the value stored into x.

With complicated names, more complicated behaviors can occur:

a[i]=i=j

This updates a[i] (with the old i) and then sets i to the same value. Whether this is more or less clear than

a[i]=j
i=j

depends both on the nature of the algorithm (is it conceptually significant that i follows the indices as they are assigned in some sort of permutation?) and on whether j is just a variable or is actually some complicated expression that does not bear repeating. (One could of course write

new_i=j
a[i]=new_i
i=new_i

but remember that additional variable names also cost in terms of readability—is new_i used later?)

Davis Herring
  • 36,443
  • 4
  • 48
  • 76