Thursday, October 14, 2010

Changing those damn locals

A “feature” of Python is that the locals dictionary of a Python frame is read-only.  What this means is that if you change a local variable during debugging ,its new value will be ignored when you resume the program.  Consider for example this trivial script:

def f(a):
    b = 2*a
    print(b)  # break here

f(2)

With PyScripter 2.1.1 if you break at the print statement and issue the commands in the interpreter:

[Dbg]>>> b = 10
[Dbg]>>> b
4
[Dbg]>>>

you can see that no matter how hard you try you cannot change the value of the local variable b.  This is not just a PyScripter issue.  See for example the feature request submitted by the author of pydev at http://bugs.python.org/issue1654367.

Well, I found a way to remove this restriction and if you try the same in PyScripter 2.3 you get:

[Dbg]>>> b = 10
[Dbg]>>> b
10
[Dbg]>>>

as you would be right to expect.  The workaround requires ctypes which is included with Python 2.5 or later.

No comments: