Import function for class-wide docstring tests
Question: I am developing on a larger project which has a class with docstrings tests
for each method. Each docstring contains a few examples/tests. The docstrings
make use of a function in another module frequently and I would like to import
it once and have it available in every docstring function test.

For example, if this is `tests.py`

    
    
    class A(object):
        def test1(self):
            """
            >>> myfunc()
            1
            """
            pass
        def test2(self):
            """
            >>> myfunc()
            1
            """
            pass
    

And this is `funcs.py`

    
    
    from tests import A
    
    # Do stuff with A
    
    def myfunc():
        return 1
    

I would like avoid modifying the above code to this:

    
    
    class A(object):
        def test1(self):
            """
            >>> from funcs import myfunc
            >>> myfunc()
            1
            """
            pass
        def test2(self):
            """
            >>> from funcs import myfunc
            >>> myfunc()
            1
            """
        pass
    

And instead do something like a class level docstring module import. I also
can't just import the function directly in the module because in my case that
would create a circular dependency.

Doctests are invoked using `python -m doctest tests.py` which has this error
output:

* * *
    
    
    File "tests.py", line 4, in tests.A.test
    Failed example:
        myfunc()
    Exception raised:
        Traceback (most recent call last):
          File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/doctest.py", line 1315, in __run
            compileflags, 1) in test.globs
          File "<doctest tests.A.test[0]>", line 1, in <module>
            myfunc()
        NameError: name 'myfunc' is not defined
    ********************************************
    1 items had failures:
    1 of   1 in tests.A.test
    ***Test Failed*** 1 failures.
    

It succeeds using the test code that has imports.

For anyone wondering why I might want to do this, my real world code is at
<https://github.com/EntilZha/ScalaFunctional/blob/master/functional/pipeline.py>.
The function I want to import is `seq` since it is an entrypoint alias to the
class `Sequence`. I would prefer to use `seq` in the docstrings since very
importantly they serve as documentation examples, `seq` has additional
behavior, and I want to start running them as my test suite to make sure they
stay up to date.


Answer: From the [`doctest` man
page](https://docs.python.org/2/library/doctest.html#what-s-the-execution-
context), "_By default, each time doctest finds a docstring to test, it uses a
shallow copy of M‘s globals_ ".

All you have to do is make sure that `myfunc` is present in the module's
globals, perhaps by adding

    
    
    from funcs import myfunc
    

to the top of the file.

