首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在docutils中使用空值

如何在docutils中使用空值
EN

Stack Overflow用户
提问于 2012-03-15 06:03:11
回答 2查看 850关注 0票数 6

我正在尝试对一个使用空值的函数运行doctest。但doctest似乎不喜欢空值...

代码语言:javascript
复制
def do_something_with_hex(c):
    """
    >>> do_something_with_hex('\x00')
    '\x00'
    """
return repr(c)

import doctest
doctest.testmod()

我看到了这些错误

代码语言:javascript
复制
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
**********************************************************************

我该怎么做才能在这样的测试用例中允许空值?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-03-15 06:11:00

您可以对所有反斜杠进行转义,或者将文档字符串更改为raw string literal

代码语言:javascript
复制
def do_something_with_hex(c):
    r"""
    >>> do_something_with_hex('\x00')
    '\x00'
    """
    return repr(c)

如果字符串中有r前缀,则反斜杠后面的字符将原封不动地包含在字符串中,而所有反斜杠都保留在字符串中。

票数 7
EN

Stack Overflow用户

发布于 2012-03-15 06:07:29

使用\\x而不是\x。当您编写\x时,Python解释器将其解释为空字节,并且空字节本身被插入到文档字符串中。例如,:

代码语言:javascript
复制
>>> def func(x):
...     """\x00"""
...
>>> print func.__doc__     # this will print a null byte

>>> def func(x):
...     """\\x00"""
...
>>> print func.__doc__
\x00
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9710987

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档