How to write an ipython alias which executes in python instead of shell?

I don't know since when IPython provides with macro. And now you can simply do this:

ipy = get_ipython()
ipy.define_macro('d', 'date')

You can put this code into any file located in ~/.ipython/profile_default/startup/, and then this macro will be automatically available when you start IPython.

However, a macro doesn't accept arguments. So pleaes keep this in mind before you choose to define a macro.


The normal way to do this would be to simply write a python function, with a def. But if you want to alias a statement, rather than a function call, then it's actually a bit tricky.

You can achieve this by writing a custom magic function. Here is an example, which effectively aliases the import statement to get, within 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)

Now it is possible to execute get statements which are aliased to import statements.

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 is extendible to arbitrary python code, and optional arguments are supported aswell.