object reuse in python doctest

You can use testmod(extraglobs={'f': initFileGenerator('')}) to define a reusable object globally.

As the doctest doc says,

extraglobs gives a dict merged into the globals used to execute examples. This works like dict.update()

But I used to test all methods in __doc__ of class before all methods.

class MyClass(object):
    """MyClass
    >>> m = MyClass()
    >>> m.hello()
    hello
    >>> m.world()
    world
    """

    def hello(self):
        """method hello"""
        print 'hello'

    def world(self):
        """method world"""
        print 'world'

To obtain literate modules with tests that all use a shared execution context (i.e. individual tests that can share and re-use results), one has to look at the relevant part of documentation on the execution context, which says:

... each time doctest finds a docstring to test, it uses a shallow copy of M‘s globals, so that running tests doesn’t change the module’s real globals, and so that one test in M can’t leave behind crumbs that accidentally allow another test to work.

...

You can force use of your own dict as the execution context by passing globs=your_dict to testmod() or testfile() instead.

Given this, I managed to reverse-engineer from doctest module that besides using copies (i.e. the dict's copy() method), it also clears the globals dict (using clear()) after each test.

Thus, one can patch their own globals dictionary with something like:

class Context(dict):
    def clear(self):
        pass
    def copy(self):
        return self 

and then use it as:

import doctest
from importlib import import_module

module = import_module('some.module')
doctest.testmod(module,
                # Make a copy of globals so tests in this
                # module don't affect the tests in another
                glob=Context(module.__dict__.copy()))