doctest environment question

Peter Otten __peter__ at web.de
Tue May 22 03:59:56 EDT 2007


tag wrote:

> Thanks again Peter. Here's something much closer to what I really want
> to do. You should be able to cut and paste this post into a file
> "post.txt". Running the command `python -c "import doctest;
> doctest.testfile('post.txt')"` gives a test failure even though
> everything works fine in an interpreted Python session. I'd like to
> find a way to make the doctest pass.
> 
>>>> def announce(f):
> ...     " Return a function which announces calls to the input
> function. "
> ...     def wrapper(*v, **k):
> ...         print "Calling %s" % f.__name__
> ...         return f(*v, **k)
> ...     return wrapper
> 
> We can rebind a function to announce calls to it:
> 
>>>> def g(): pass
> ...
>>>> g = announce(g)
>>>> g()
> Calling g
> 
> Or we can use decorator syntax:
> 
>>>> @announce
> ... def f(): pass
> ...
>>>> f()
> Calling f
> 
> Here's a function which rebinds a function at the top level of a
> module (it won't work for nested functions).
> 
>>>> def announce_function(f):
> ...     " Rebind f within a module so that calls to f are announced. "
> ...     import inspect
> ...     setattr(inspect.getmodule(f), f.__name__, announce(f))

inspect.getmodule(f) returns None because f() is not defined in a module.
You can either move f() to a helper module and then

from helper_module import f

or modify anouncement_function() to not rely on that non-existent module

>>> def announce_function(f):
...     " Rebind f within a module so that calls to f are announced. "
...     f.func_globals[f.__name__] = announce(f)
...

 
> Let's give it a try. This next works fine in an interactive Python
> session but fails when doctested.
> 
>>>> def h(): pass
> ...
>>>> announce_function(h)
>>>> h()
> Calling h

Even when it works, implicitly modifying global variables is bad style.

Peter



More information about the Python-list mailing list