Skip to content Skip to sidebar Skip to footer

Ipython Magic Print Variables On Assignment

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, t

Solution 1:

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.

Solution 2:

Try the following for older versions of IPython…

from IPython.core.inputtransformer import InputTransformer
import re

classPrintAssignment(InputTransformer):
    def__init__(self):
        self.assignment = re.compile('^([a-z]+) =')
        self.most_recent_line = Nonedefpush(self, line):
        self.most_recent_line = line
        return line
    defreset(self):
        ifnot self.most_recent_line: return
        match = self.assignment.match(self.most_recent_line)
        self.most_recent_line = Noneif match: return match.group(1)

And then register this input handler with

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

Post a Comment for "Ipython Magic Print Variables On Assignment"