tags:

views:

52

answers:

2

Hi, is there any way to doctest locally defined functions? As an example I would want

def foo():
  """ >>> foo()
  testfoo"""

  def foo2():
    """ >>> 1/0 """ 
    print 'testfoo'

  foo2()

to NOT pass the test. But still I would not want to make foo2 global for the entire module...

+1  A: 

You just have a whitespace problem -- if you fix it, for example as follows:

def foo():
  """
    >>> foo()
    testfoo"""

  def foo2():
    """ >>> 1/0 """ 
    print 'testfoo'

  foo2()

if __name__ == '__main__':
  import doctest
  doctest.testmod()

the test passes just fine.

Alex Martelli
This is a typo and obfuscates my intention: I want the test __NOT__ to pass.. I want to get something like "ZeroDivisionError: integer division or modulo by zero" due to the doctest string in foo2. The question is how to doctest subroutines.
cycyc
Ah, I see. A **nested** function's docstring is not visible where the (nested) function object itself doesn't exist -- and in your code, the function object for foo2 only exists during the execution of the outer function foo. (In the normal closure-factory case where the outer function *returns* the inner-function object, rather than just using it internally as an implementation detail, you have more options of course). Basically, it **must** be foo's job to somehow surface foo2's otherwise-hidden docstring, because nobody else can possibly do it (foo2 doesn't **exist** for anybody else!-).
Alex Martelli
A: 

Thanks. I already feared there would be no way around code outside the docstring. Still I thought there might be a trick to import the locals of a function and thus get access to nested functions. Anyhow, a solution using Alex' approach would read

def foo(debug=False):
  """
     >>> foo()
     testfoo
     >>> foo(debug=True)
     """

  def foo2():
    """
       >>> 1/0"""
    print 'testfoo'


  if debug :
    import doctest
    for f in [foo2]: doctest.run_docstring_examples(f,locals())

  foo2()

Now the only question is how to automate this approach, so one has something like

for f in locals().values(): doctest.run_docstring_examples(f,locals())

but without the imported and built in functions and variables.

cycyc