You can use the IPython In and Out variables that contain the entered commands / operators and the corresponding output (if any) of these operators.
So, a naive approach would be to use these variables as the basis for defining the %last magic method.
However, since not all statements necessarily generate output, In and Out are not synchronous.
So, the approach I came with was to parse In and look for occurrences = and parse these lines for output:
def last_assignment_value(self, parameter_s=''): ops = set('()') has_assign = [i for i,inpt in enumerate(In) if '=' in inpt]
And finally, to make your own custom command in IPython:
get_ipython().define_magic('last', last_assignment_value)
And now you can call:
%last
And this will output the term assigned as a string (which may not be the way you want).
However, there is a caveat: if you entered the wrong input, which included the appointment; for example: (a = 2) , this method will pick it up. And, if your assignment is associated with variables: for example, a = name , this method will return name and not the value of the name.
Given this limitation, you can use the parser module to try to evaluate an expression like this (which can be added to last_assignment_value in the last if statement ):
import parser def eval_expression(src): try: st = parser.expr(src) code = st.compile('obj.py') return eval(code) except SyntaxError: print 'Warning: there is a Syntax Error with the RHS of the last assignment! "%s"' % src return None
However, given the potential flaws of eval , I left this inclusion to you.
But, to be honest, a really useful method will include parsing instructions to verify the validity of the input found, as well as the input in front of it, etc.
LITERATURE: https://gist.github.com/fperez/2396341