By default, each time testmod() finds a docstring to test, it uses a copy of M's globals, so that running tests on a module 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. This means examples can freely use any names defined at top-level in M, and names defined earlier in the docstring being run.
You can force use of your own dict as the execution context by passing
globs=your_dict
to testmod() instead. Presumably this
would be a copy of M.__dict__
merged with the globals from other
imported modules.
See About this document... for information on suggesting changes.