[IPython-user] pysh variable substituion and scope

Fernando Perez fperez.net at gmail.com
Sat Jun 3 19:35:11 CDT 2006


On 6/3/06, Krishna Mohan Gundu <gkmohan at gmail.com> wrote:
> Hello All,
>
> It looks like during variable substituion the scope is limited to the
> global scope rather than the scope of the calling function. Can the
> current behavior be modified to include the proper scope? In the
> following example
>
> ===
> gvar = 0
>
> def pysh_test(lvar):
>    echo "$gvar $lvar"
>
> pysh_test(0)
> ===
>
> gvar is substitued but lvar cannot be found in the scope

Well, here you are relying on a convenience of ipython which
automatically rewrites your interactive input in the definition:

longs[~]|1> def foo():
        |.>     echo "hi"
line out:     _ip.system('echo "hi"')
        |.>

But the code:

def foo():
    echo "hi"

is NOT valid python by itself.  IPython's convenience on-the-fly
rewriting can only go so far.  For uses like these, simply write valid
python code in the first place, and you can have much better control
of what's going on.

> `ipython -ipthondir` seems to be broken in SVN. Even with this option
> it looks for "~/.ipython/ipy_user_conf.py"

Yup, thanks for the report.  Fixed in SVN (r1346).

> Finally, I would like to ask why %echo differs in behavior from the
> shell echo command. It escapes '#' when printed and I dont remember
> but I noticed it produces some extra spaces with certain prints.
>
> ===
> krishna at master[ipython]|1> echo "# hash is escaped?"
> \# hash is escaped?
> ===

Yes, # is escaped, and I honestly don't really know why.  The code
that does this is in iplib.py, around line 440:

http://projects.scipy.org/ipython/ipython/browser/ipython/trunk/IPython/iplib.py#L440


        # utility to expand user variables via Itpl
        self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
                                                 self.user_ns))

I unfortunately did not comment WHY I was escaping hashes, and right
now I can't think of the reason.  But since it obviously was explicit,
I'm very reluctant to change this, since I'm afraid of breaking
something 3 days before a release.  self.note("always comment this
kind of stuff!")

I spent some time searching the SVN history, but this is very old,
before the cvs2svn transition, and honestly if I didn't actually
document the issue, all I would probably find is that it appeared at
some point without further details.

I'll think about it further; if anyone sees a good reason for this
behavoir, please pitch in.

Cheers,

f




More information about the IPython-user mailing list