6

I'm trying to run doctest on a function that works with nulls. But doctest doesn't seem to like the nulls...

def do_something_with_hex(c):
    """
    >>> do_something_with_hex('\x00')
    '\x00'
    """
return repr(c)

import doctest
doctest.testmod()

I'm seeing these errors

Failed example:
    do_something_with_hex(' ')
Exception raised:
    Traceback (most recent call last):
      File "C:\Python27\lib\doctest.py", line 1254, in __run
        compileflags, 1) in test.globs
    TypeError: compile() expected string without null bytes
**********************************************************************

What can I do to allow nulls in test cases like this?

Mark Irvine
  • 1,349
  • 14
  • 24

2 Answers2

7

You could escape all of the backslashes, or alternatively change your docstring to a raw string literal:

def do_something_with_hex(c):
    r"""
    >>> do_something_with_hex('\x00')
    '\x00'
    """
    return repr(c)

With the r prefix on the string a character following a backslash is included in the string without change, and all backslashes are left in the string.

Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
3

Use \\x instead of \x. When you write \x, the Python interpreter interprets it as a null byte, and the null byte itself gets inserted into the docstring. E.g.,:

>>> def func(x):
...     """\x00"""
...
>>> print func.__doc__     # this will print a null byte

>>> def func(x):
...     """\\x00"""
...
>>> print func.__doc__
\x00
Tamás
  • 47,239
  • 12
  • 105
  • 124