6
votes

Is there a parameter in IPython to print the variables each time I assign them ?

Currently:

In [1]: a = 5

In [2]: a
Out[2]: 5

In [3]: b = a + 1

In [4]: b
Out[4]: 6

In matlab, the variable is printed unless one writes a ; at the end, in ipython I would like to activate this with a magic function like so:

In [1]: %printassignment

In [2]: a = 5
a = 5

In [3]: b = a + 1
b = 6

I could write my own magic, but I'm pretty sure that's something that is so standard people would craft a super tuned, standard, function. The feature is especially useful for beginners.

2
After using ipython for some time, I find that MATLAB/Octave auto print to be a pain. I keep forgetting the ;. If I want to see a calculation in Ipython I just omit the assignment. I can always do x=_ next if I want to save the displayed value. - hpaulj
I totally agree, that's why I don't say it should be the default, or even worse, I totally do not recommend it in scripts. However, I want to use it in my classes for young students, I really want to emphasize that the "python calculator" is as easy and intuitive as the "normal calculator". About x = _ I totally agree ! But then in the history when I write "x = "<UP> to recompute, I don't get the expression, I get _, which is not useful. Moreover when using it live in front of the students, it's easier for them to follow if they want to write down the intermediary values. - Robert Vanden Eynde

2 Answers

12
votes

As of IPython 6.2, this exists, but the command to turn it on is really long:

%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'

You can set it in your ipython_config.py, if you want it to be on by default:

c = get_config()
c.InteractiveShell.ast_node_interactivity = 'last_expr_or_assign'

It only triggers when the assignment target is a simple name; assignments like arr[i] = val or obj.attr = 3 will not auto-print.

0
votes

Try the following for older versions of IPython…

from IPython.core.inputtransformer import InputTransformer
import re

class PrintAssignment(InputTransformer):
    def __init__(self):
        self.assignment = re.compile('^([a-z]+) =')
        self.most_recent_line = None
    def push(self, line):
        self.most_recent_line = line
        return line
    def reset(self):
        if not self.most_recent_line: return
        match = self.assignment.match(self.most_recent_line)
        self.most_recent_line = None
        if match: return match.group(1)

And then register this input handler with

ip = get_ipython()
ip.physical_line_transforms.append(PrintAssignment())