<div class="gmail_quote">On 30 November 2011 13:56, Kevin Buchs <span dir="ltr"><<a href="mailto:kevin.buchs@gmail.com">kevin.buchs@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">

<div>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.</div>

</blockquote><div><br>The function object is copied (at least, a reference to it is) - it is a variable like any other.<br> </div><blockquote class="gmail_quote" style="margin: 0pt 0pt 0pt 0.8ex; border-left: 1px solid rgb(204, 204, 204); padding-left: 1ex;">

<div>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.</div>

</blockquote><div><br>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:<br>

<br>In [1]: from x import *<br><br>In [2]: a()<br><br>In [3]: b<br>---------------------------------------------------------------------------<br>NameError                                 Traceback (most recent call last)<br>

/home/thomas/code/virtualenvs/ipy-trunk/<ipython-input-3-3b5d5c371295> in <module>()<br>----> 1 b<br><br>NameError: name 'b' is not defined<br><br>In [4]: import sys<br><br>In [5]: sys.modules['x'].b<br>

Out[5]: 1000<br> </div><blockquote class="gmail_quote" style="margin: 0pt 0pt 0pt 0.8ex; border-left: 1px solid rgb(204, 204, 204); padding-left: 1ex;">
<div></div><div>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? </div></blockquote></div><br>

'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).<br><br>Thomas<br>