How do I write an ipython alias that runs in python instead of a shell?

We can define alias in ipython with a magic function %alias

like:

>>> d
NameError: name 'd' is not defined
>>> %alias d date
>>> d
Fri May 15 00:12:20 AEST 2015

      

This results in a shell command date

when d

typed into ipython.

But I want to define an alias to execute some python code in the current scope of the interpreter, not a shell command. Is it possible? How can we make this alias?

I work a lot in the interactive interpreter and it can save me a lot of commands that I repeat often, and it also prevents some common typos.

+3


source to share


1 answer


The usual way to do this is to just write a python function with def

. But if you want to use a statement alias rather than a function call, then it is actually a bit tricky.

This can be done by writing a special magic function. Here is an example, which effectively psevdoniziruet operator import

up get

in the REPL.

from IPython.core.magic_arguments import argument, magic_arguments

@magic_arguments()
@argument('module')
def magic_import(self, arg):
    code = 'import {}'.format(arg)
    print('--> {}'.format(code))
    self.shell.run_code(code)

ip = get_ipython()
ip.define_magic('get', magic_import)

      

You can now execute statements get

that are smoothed to statements import

.



Demo:

In [1]: get json
--> import json

In [2]: json.loads
Out[2]: <function json.loads>

In [3]: get potato
--> import potato
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<string> in <module>()

ImportError: No module named potato

In [4]: 

      

Of course this extends to arbitrary python code, and optional arguments are supported as well .

+5


source







All Articles