From 399d860cf111f449b79d87807ecce03c916d6591 2013-01-02 16:19:12 From: Bradley M. Froehle Date: 2013-01-02 16:19:12 Subject: [PATCH] Merge pull request #2731 from bfroehle/rpush_local_scope %Rpush: Look for variables in the local scope first. --- diff --git a/IPython/extensions/rmagic.py b/IPython/extensions/rmagic.py index 9fc1a0f..df45d68 100644 --- a/IPython/extensions/rmagic.py +++ b/IPython/extensions/rmagic.py @@ -178,8 +178,9 @@ class RMagics(Magics): return value @skip_doctest + @needs_local_scope @line_magic - def Rpush(self, line): + def Rpush(self, line, local_ns=None): ''' A line-level magic for R that pushes variables from python to rpy2. The line should be made up @@ -199,10 +200,16 @@ class RMagics(Magics): Out[11]: array([ 6.23333333]) ''' + if local_ns is None: + local_ns = {} inputs = line.split(' ') for input in inputs: - self.r.assign(input, self.pyconverter(self.shell.user_ns[input])) + try: + val = local_ns[input] + except KeyError: + val = self.shell.user_ns[input] + self.r.assign(input, self.pyconverter(val)) @skip_doctest @magic_arguments() diff --git a/IPython/extensions/tests/test_rmagic.py b/IPython/extensions/tests/test_rmagic.py index a5849e9..fc757d1 100644 --- a/IPython/extensions/tests/test_rmagic.py +++ b/IPython/extensions/tests/test_rmagic.py @@ -14,6 +14,20 @@ def test_push(): np.testing.assert_almost_equal(np.asarray(rm.r('X')), ip.user_ns['X']) np.testing.assert_almost_equal(np.asarray(rm.r('Y')), ip.user_ns['Y']) +def test_push_localscope(): + """Test that Rpush looks for variables in the local scope first.""" + ip.run_cell(''' +def rmagic_addone(u): + %Rpush u + %R result = u+1 + %Rpull result + return result[0] +u = 0 +result = rmagic_addone(12344) + ''') + result = ip.user_ns['result'] + np.testing.assert_equal(result, 12345) + def test_pull(): rm = rmagic.RMagics(ip) rm.r('Z=c(11:20)')