doctest environment question

Peter Otten __peter__ at web.de
Mon May 21 13:53:03 EDT 2007


thomas.guest at gmail.com wrote:

> I'm not making progress with the following and would appreciate any
> help.
> 
> Here's an interpreted Python session.
> 
>>>> import sys
>>>> def f(): pass
> ...
>>>> this_module = sys.modules[__name__]
>>>> delattr(this_module, 'f')
>>>> f()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> NameError: name 'f' is not defined
> 
> Suppose I want to doctest this behaviour. I cut and paste the above
> into a file "test.txt" then run:
> 
> python -c "import doctest; doctest.testfile('test.txt')"
> 
> This gives me unexpected test failures:
> 
> python -c "import doctest; doctest.testfile('test.txt')"
> **********************************************************************
> File "test.txt", line 5, in test.txt
> Failed example:
>     delattr(this_module, 'f')
> Exception raised:
>     Traceback (most recent call last):
>       File "/Library/Frameworks/Python.framework/Versions/2.5/lib/
> python2.5/doctest.py", line 1212, in __run
>         compileflags, 1) in test.globs
>       File "<doctest test.txt[3]>", line 1, in <module>
>         delattr(this_module, 'f')
>     AttributeError: f
> **********************************************************************
> File "test.txt", line 6, in test.txt
> Failed example:
>     f()
> Expected:
>     Traceback (most recent call last):
>       File "<stdin>", line 1, in <module>
>     NameError: name 'f' is not defined
> Got nothing
> **********************************************************************
> 1 items had failures:
>    2 of   5 in test.txt
> ***Test Failed*** 2 failures.

The doctest code is executed in a module without a __name__, it seems.
Unfortunately (in this case) the builtin module serves as a fallback
helping out with its own name:

>>> __name__
'__main__'
>>> del __name__
>>> __name__
'__builtin__'


What to do about it? doctest could be changed to execute code snippets in a
module with a name and a sys.modules entry though I don't see much benefit
here.

Peter



More information about the Python-list mailing list