6 ms·
A caveat: this example shows that you can read the value of a local variable, not that you can modify it. If you try actually assigning to an element of f_local
by teraflop 9y ago
A caveat: this example shows that you can read the value of a local variable, not that you can modify it. If you try actually assigning to an element of f_locals, as opposed to just dereferencing it, you'll find that the modification doesn't take effect due to optimizations in CPython's bytecode interpreter.
- arghwhat 9y agoMaybe they're running an alternative Python implementation? There are quite a few.
- teraflop 9y agoNo, I'm saying that the OP's code isn't actually modifying a local variable, because it never assigns to an element of the f_locals dictionary.
- eesmith 9y agoTo further clarify, it modifies the value of an object referenced by a local variable.
- arghwhat 9y agoYou were referring to CPython implementation details, which do not apply to Jython, IronPython, PyPy, and many more. Alternative Python implementations do not follow all CPython implementation details. In other words, if this is not part of the Python specification, it might work on other Python implementations even if it does not work on CPython.
- dr_zoidberg 9y ago> ...Jython... Which is Java with Python syntax...
- arghwhat 9y agoNo. Jython is a full implementation of Python in Java. Last I collided with it, it was terribly slow, but that is not the point here. Some of these alternative implementations are very interesting. PyPy is JIT'ed, and insanely fast compared to CPython. IronPython, IIRC, has no GIL.
- Demiurge 9y agoThat's a good point, I modified the object to which the variable was referring to (session), not the local variable itself.
- jamesdutc 9y agoBut tuples (and cells) are mutable in pure CPython if you believe strongly enough. See: https://gist.github.com/llllllllll/b1ac68a6b77535a64c0b13bfd887c05a https://gist.github.com/llllllllll/b1ac68a6b77535a64c0b13bfd... https://gist.github.com/dutc/d2ff9f17a0520d233b2d197d1dafa1a2 https://gist.github.com/dutc/d2ff9f17a0520d233b2d197d1dafa1a... https://twitter.com/__qualname__/status/867928378040438784 https://twitter.com/__qualname__/status/867928378040438784
- rtpg 9y agothere's a secret hack to get your `f_locals` changes to propogate back exec( code_fragment, frame.f_globals, frame.f_locals ) # update locals ctypes.pythonapi.PyFrame_LocalsToFast(ctypes.py_object(frame), ctypes.c_int(0)) This sets the values back into the right place on the frame you were operating on. https://pydev.blogspot.jp/2014/02/changing-locals-of-frame-frameflocals.html https://pydev.blogspot.jp/2014/02/changing-locals-of-frame-f...