InteractiveConsole and namespace

Chris Rebert clp2 at rebertia.com
Sun Aug 29 02:05:12 CEST 2010


On Sat, Aug 28, 2010 at 2:37 PM, David ROBERT <david at ombrepixel.com> wrote:
> Hi all,
>
> I want to use an InteractiveConsole at some stage in a program to
> interact with the local namespace: access, but also modify objects.
> When the interactive console ends (ctrl-d) I want the program to
> continue processing with the variables that may have been modified
> interactively.
>
> The code below works (block invoking the console is not in a
> function). During the interactive session, I can read value of a, I
> can change value of a and the new value is "updated" in the block
> namespace.
>
> import code
> if __name__ == '__main__':
>    a=1
>    c = code.InteractiveConsole(locals())
>    c.interact()  # Here I interactively change the value of a (a=2)
>    print "Value of a: ", a
>
> print returns --> Value of a: 2
>
> However, on the other code below (the console is invoked from within a
> function block), during the interactive session, I can read value of
> a, I can change value of a. But the local namespace of the function is
> not updated:
>
> import code
> def test():
>    a=1
>    c = code.InteractiveConsole(locals())
>    c.interact() # Here I interactively change the value of a (a=2)
>    print "Value of a: ", a
>
> if __name__ == '__main__':
>    test()
>
> print returns --> Value of a: 1
>
> I need to run the InteractiveConsole from a function block. I tried
> different things with the local and parent frames (sys._getframe())
> but nothing successful. If I put a in the global namespace it works,
> but I would like to
[...]
> understand what the
> problem is.

Read http://docs.python.org/library/functions.html#locals (emphasis added):

"locals()
[...]
Note: The contents of this dictionary should not be modified;
***changes may not affect the values of local and free variables used
by the interpreter***."

At the top-level / module scope, it just so happens that `locals() is
globals() == True`; and unlike locals(), globals() does not have the
aforequoted limitation.

I don't know if there's a non-ugly workaround.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list