[IPython-dev] dictionaries and %run oddity

Thomas Kluyver takowl at gmail.com
Wed Nov 30 09:28:49 EST 2011

On 30 November 2011 13:56, Kevin Buchs <kevin.buchs at gmail.com> wrote:

> When I %run a command, it is given its own namespace, say N1. Any
> variables defined in that namespace are copied to the original namespace of
> my iPython session, say N0. The function definition is not copied, however.

The function object is copied (at least, a reference to it is) - it is a
variable like any other.

> When I then invoke (not %run) the function from N0, it runs in N1. Then
> any variables created in N1 are NOT copies to N0. So, if I would %run the
> function definition and invocation in one command, then any variables
> defined are copied back.

Functions run in the scope where they were defined - even though your
namespace has a reference to a, Python knows that a was defined in module
x. If you do "from x import * " with your example, then do a(), it behaves
the same way. Here it is defining an integer:

In [1]: from x import *

In [2]: a()

In [3]: b
NameError                                 Traceback (most recent call last)
/home/thomas/code/virtualenvs/ipy-trunk/<ipython-input-3-3b5d5c371295> in
----> 1 b

NameError: name 'b' is not defined

In [4]: import sys

In [5]: sys.modules['x'].b
Out[5]: 1000

> What does not make sense to me is if I declare a variable global in a
> function declared in a certain namespace, shouldn't that mean it is
> available in the global namespace?

'global' is a bit misleading - in Python, it means global to that module.
By design, there isn't a shared global namespace (well, you can modify
builtins, but it's frowned upon).

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/ipython-dev/attachments/20111130/b216050b/attachment.html>

More information about the IPython-dev mailing list