Search This Blog

Monday, April 22, 2013

How to paste into Python interpreter a code snippet for testing

While working on a bigger Python code module you would like to test a small part of it quickly. When you try to copy it directly to your Python interpreter (python, bpython, ipython) you get IndentationError: unexpected indent or SyntaxError: invalid syntax error messages.

Problem

How to copy a code snippet into ipython.

Solution

Example 1
 
a=True
if a :
    print "true"

else:
    print "false"

Example 2
 
class Test:
    def f(self):
        print("hello f")

    def f2(self):
        print("hello f2")

c=Test()
c.f()

To test example 1 or 2 code we are going to use ipython. To instruct the interpreter that it shouldn't  auto-format or auto-indent we use the %cpaste magic. An example below shows how to use it.
 
user@server:# ipython
Python 2.7.3 (default, Aug  1 2012, 05:14:39)
Type "copyright", "credits" or "license" for more information.

IPython 0.12.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: %cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:a=True
:if a :
:    print "true"
:
:else:
:    print "false"
:
:--

true

References
  1. http://stackoverflow.com/questions/10886946/how-does-ipythons-magic-paste-work

No comments:

Post a Comment