Reputation: 3346
I would like to add some syntax changes to (my installation of) IPython. For example, I might want to use \+
to mean operator.add
. I imagine that I can insert some code that would process the input and turn it into actual (I)Python, and then IPython can do its own processing. But I don't know where to put that code.
(Disclaimer: Don't do it for production code, or code that's intended for other people to see/use.)
Upvotes: 4
Views: 147
Reputation: 2816
Here is an example of how to transform "\+ a b"
to "a + b"
.
from IPython.core.inputtransformer import StatelessInputTransformer
@StatelessInputTransformer.wrap
def my_filter(line):
words = line.split()
if line.startswith(r'\+ ') and len(words) == 3:
return '{} + {}'.format(*words[1:])
return line
ip = get_ipython()
ip.input_transformer_manager.physical_line_transforms.insert(0, my_filter())
Note that this is all string based. This hook executes in an unevaluated context. It means that you can't do conditional transformation based on which value is a
or b
. A magic would best suit your need in that case.
Moreover, you have to be careful when parsing input string. In my example, the following is broken \+ (a * b) c
because of the split. In that case, you will need a tokenization tool. IPython provides one with TokenInputTransformer
. It works like StatelessInputTransformer
but it is called with a list of tokens instead of the whole line.
Simply run this code to add the filter. If you want it to be available as you start IPython, you can save it as a .py
or .ipy
file and put it in
~/.ipython/profile_*/startup
https://ipython.org/ipython-doc/dev/config/inputtransforms.html
Upvotes: 2