unit test nested functions

Benji York benji at benjiyork.com
Sat Jul 23 18:20:08 CEST 2005


Raymond Hettinger wrote:
> [Andy]
>>How can you unit test nested functions? 

> For whitebox testing, you could make an inner function visible by
> binding it to the enclosing function's attribute namespace.
> 
>    def f(x):
>        def g(y):
>           . . .
>        f.g = g        # make g visible as an attribute of f
>        . . .

Note that when using this technique, f.g will not be bound until after 
you call the function:

 >>> def f(x):
...     def g(y):
...         pass
...     f.g = g
...
 >>> f
<function f at 0xb7df3df4>
 >>> f.g
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
AttributeError: 'function' object has no attribute 'g'
 >>> f(1)
 >>> f.g
<function g at 0xb7df3e2c>
--
Benji York





More information about the Python-list mailing list