6

null で動作する関数で doctest を実行しようとしています。しかし、doctest はヌルが気に入らないようです...

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

import doctest
doctest.testmod()

これらのエラーが表示されます

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
**********************************************************************

このようなテスト ケースで null を許可するにはどうすればよいですか?

4

2 に答える 2

7

すべてのバックスラッシュをエスケープするか、docstring を生の文字列リテラルに変更できます。

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

文字列にr接頭辞を付けると、バックスラッシュに続く文字はそのまま文字列に含まれ、バックスラッシュはすべて文字列に残されます

于 2012-03-14T22:11:00.133 に答える
3

\\xの代わりに使用し\xます。を記述する\xと、Python インタープリターはそれを null バイトとして解釈し、null バイト自体が docstring に挿入されます。例えば、:

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

>>> def func(x):
...     """\\x00"""
...
>>> print func.__doc__
\x00
于 2012-03-14T22:07:29.123 に答える