>> my_function(b'\0') '6e340b9cffb37a989ca544e...">

ValueError: source line 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()

      

Expected behavior: 1 test run

Actual behavior: The exception ValueError

is thrown from within doctest.py

.

I tried using literal b'\x00'

also with the same result. How do I use null bytes in doctest? What exactly is the problem, and is there any fix or not-too-ugly workaround?

+3


source to share


2 answers


Your doctrines become double. First, Python applies a backslash \0

to null byte in the docstring itself, and then doctest

tries to run the object after >>>

as Python code and encounters an error because backslash handling has already been applied.

This will also be a problem for anyone just trying to print your docstring or trying to call help

for your function.



As with regular expressions, 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()

      

+3


source


If you want the string to contain a backslash, you need to escape it with another backslash. Otherwise, it tries to avoid the next character.

In your case b'\0'

will replace \0

with a null character and hence your error. Try this instead:



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

      

0


source







All Articles