pythonuser-interfaceread-eval-print-loop

Copying and pasting Python REPL examples


Many Python examples are shown as Python REPL sessions, for example:

>>> class eg(object):
...     def __init__(self, name):
...             self.name = name
...     def hi(self):
...             print "Hi %s" % (self.name)
... 
>>> greeter = eg("Bob")
>>> greeter.hi()
Hi Bob
>>> 

But if I try to copy and paste that code into another python interpreter session, I get errors:

>>> >>> class eg(object):
  File "<stdin>", line 1
    >>> class eg(object):
     ^
SyntaxError: invalid syntax
>>> ...     def __init__(self, name):
  File "<stdin>", line 1
    ...     def __init__(self, name):
    ^

To get it to run, I would have to either..

How else can I avoid the problem?


Solution

  • How to run/adopt "the output of Pythons REPL"

    Copy without the shell prompt in the first place (though I don't know how to do it on Google Chrome, for example).

    Why the doctest format is used

    Save the following to documentation.txt:

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
    eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
    minim veniam, quis nostrud exercitation ullamco laboris nisi ut
    aliquip ex ea commodo consequat. 
    
    >>> class eg(object):
    ...     def __init__(self, name):
    ...             self.name = name
    ...     def hi(self):
    ...             print "Hi %s" % (self.name)
    ... 
    >>> greeter = eg("Bob")
    >>> greeter.hi()
    Hi Bob
    >>>
    
    Duis aute irure dolor in reprehenderit in voluptate velit esse cillum
    dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
    proident, sunt in culpa qui officia deserunt mollit anim id est
    laborum.
    

    Run:

    $ python -c "import doctest; doctest.testfile('documentation.txt')" -v
    

    Output:

    Trying:
        class eg(object):
            def __init__(self, name):
                    self.name = name
            def hi(self):
                    print "Hi %s" % (self.name)
    Expecting nothing
    ok
    Trying:
        greeter = eg("Bob")
    Expecting nothing
    ok
    Trying:
        greeter.hi()
    Expecting:
        Hi Bob
    ok
    1 items passed all tests:
       3 tests in doctest.txt
    3 tests in 1 items.
    3 passed and 0 failed.
    Test passed.
    

    If you add the following snippet at the end of your module it will test all code in its docstrings:

    if __name__=="__main__":
       import doctest; doctest.testmod()
    

    QED