[IPython-user] customized magic function limitation

belinda thom bthom at cs.hmc.edu
Thu Jan 11 00:27:51 CST 2007


Ville,


On Jan 10, 2007, at 10:04 PM, Ville M. Vainio wrote:

> On 1/11/07, belinda thom <bthom at cs.hmc.edu> wrote:
>
>> Is there a way to write a customized magic function that takes
>> multiple arguments?
>
> The arg is just a string, yohU have to split it yourself, using
> genutils.arg_split or even just normal string split() method.

Thanks for the input!

I'm not sure if this is what you'd meant, but here's how I've  
implemented your advice:

In [7]: %t2??
Type:           Magic function
<snip>
Definition:     %t2(self, arg)
Source:
def dtest(self, arg):
     self.api.ex("print %s, %s" % (arg.split().pop(0),arg.split().pop 
(1)))

In [8]: %t2 "hi there"
hi, there

It appears that w/two args, you must enclose all w/in matching string  
markers ("" or ''), which makes sense given that's how Python  
recognizes strings.

What is still confusing to me about magic commands is why I can call  
one w/a variable that has not yet been defined---provided the magic  
command is doing an import---but I can't for another kind of magic  
function (appended). There must be some pretty-slick parse/evaluate  
stuff going on.

Thanks,
--b

==============

W/import, no naming error:

93 % ipython
<snip>
IPython 0.7.4.svn.r2010 -- An enhanced Interactive Python.
<snip>
In [1]: %imp??
Type:           Magic function
<snip>
Definition:     %imp(self, arg)
Source:
def doimp(self, arg):
     """
     does (another) import / reload sequence of file arg.
     """
     self.api.ex("import %s; reload(%s)" % (arg,arg))

In [2]: %imp dice

Without import, I get a naming error:

94 % ipython
<snip>
IPython 0.7.4.svn.r2010 -- An enhanced Interactive Python.
<snip>
In [1]: %t1??
Type:           Magic function
<snip>
Definition:     %t1(self, arg)
Source:
def dtest(self, arg):
     self.api.ex("print %s" % arg)

In [2]: %t1 dice
------------------------------------------------------------------------ 
---
exceptions.NameError                                 Traceback (most  
recent call last)
/Users/bthom/belinda/mills/aicourse/python_exs/<ipython console>
<snip>
/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site- 
packages/IPython/ipapi.py in ex(self, cmd)
     210     def ex(self,cmd):
     211         """ Execute a normal python statement in user  
namespace """
--> 212         exec cmd in self.user_ns
     213
     214     def ev(self,expr):
/Users/bthom/belinda/mills/aicourse/python_exs/<string>
NameError: name 'dice' is not defined



More information about the IPython-user mailing list