ValueError:源代码字符串不能包含空字节(ValueError: source code string cannot contain null bytes)

编程入门 行业动态 更新时间:2024-10-28 18:28:35
ValueError:源代码字符串不能包含空字节(ValueError: source code string cannot contain null bytes) import hashlib def my_function(bytes_): """ >>> my_function(b'\0') '6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d' """ return hashlib.sha256(bytes_).hexdigest() if __name__ == "__main__": import doctest doctest.testmod()

预期行为: 1次测试通过

实际行为:从doctest.py引发ValueError异常。

我尝试使用b'\x00'文字也有相同的结果。 如何在doctest中使用空字节? 究竟是什么问题,是否有任何修复或不太丑陋的解决方法?

import hashlib def my_function(bytes_): """ >>> my_function(b'\0') '6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d' """ return hashlib.sha256(bytes_).hexdigest() if __name__ == "__main__": import doctest doctest.testmod()

Expected behaviour: 1 test passes

Actual behaviour: ValueError exception is raised from within doctest.py.

I've tried to use b'\x00' literal as well with the same result. How to use null bytes in doctest? What exactly is the problem here, and is there any fix or not-too-ugly workaround?

最满意答案

你的doctest正在进行双重解析。 首先,Python应用反斜杠处理将\0转换为docstring本身的空字节,然后doctest尝试在>>>之后运行事物作为Python代码并遇到错误,因为已经应用了反斜杠处理。

对于只是尝试打印文档字符串或尝试调用函数help人来说,这也是一个问题。

与正则表达式一样,要避免第一层反斜杠处理,请使用原始字符串表示法:

def my_function(bytes_): r""" >>> my_function(b'\0') '6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d' """ return hashlib.sha256(bytes_).hexdigest()

Your doctest is getting double-parsed. First, Python applies backslash processing to convert \0 to a null byte in the docstring itself, and then doctest tries to run the thing after the >>> as Python code and encounters an error because backslash processing has already been applied.

This would also be a problem for anyone just trying to print your docstring, or trying to call help on your function.

As with regexes, to avoid the first layer of backslash processing, use raw string notation:

def my_function(bytes_): r""" >>> my_function(b'\0') '6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d' """ return hashlib.sha256(bytes_).hexdigest()

更多推荐

本文发布于:2023-07-07 04:22:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1058930.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   字节   源代码   ValueError   source

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!