How to get the value of the last assigned variable in iPython?

I am a complete newbie of iPython, but I was wondering if there is a way to get the value of the last assigned variable:

In [1]: long_variable_name = 333 In [2]: <some command/shortcut that returns 333> 

In R we have .Last.value :

 > long_variable_name = 333 > .Last.value [1] 333 
+6
source share
2 answers

There is a shortcut for the last returned object, _ .

 In [1]: 1 + 3 Out[1]: 4 In [2]: _ Out[2]: 4 
+17
source

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] #find all line indices that have `=` has_assign.sort(reverse=True) #reverse sort, because the most recent assign will be at the end for idx in has_assign: inpt_line_tokens = [token for token in In[idx].split(' ') if token.strip() != ''] # indices = [inpt_line_tokens.index(token) for token in inpt_line_tokens if '=' in token and not any((c in ops) for c in token)] #Since assignment is an operator that occurs in the middle of two terms #a valid assignment occurs at index 1 (the 2nd term) if 1 in indices: return ' '.join(inpt_line_tokens[2:]) #this simply returns on the first match with the above criteria 

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

+2
source

Source: https://habr.com/ru/post/956724/


All Articles