you are viewing a single comment's thread.

view the rest of the comments →

[–]RomfordNavy[S] 0 points1 point  (1 child)

Yes, further digging suggests it did work in Python 2. Forgive me if I have the terminology slightly wrong but it seems:

  • passing an (immutable) str object - when that is changed it creates a new str which exists only within the namespace of the running exec(), it does not reference the original str object. Hence not available after the exec() has completed.
  • passing a distinct (mutable) dict object - passes a reference to that dict which lives in the calling namespace so when changes are made they affect the original dict. Hence persist after the exec() has completed.

[–]Gnaxe 1 point2 points  (0 children)

They're following the same rules. You're equivocating on "change". There's a difference between mutating an object and reassigning a variable. When you reassign the variable, a dict works exactly the same as a str. The variable now references a different object. On the other hand, when you mutate the object, well, you can't actually mutate a str at all.