• Kirill Smelkov's avatar
    util: Fix ashex for Python3 · 7a7370e6
    Kirill Smelkov authored
    	s = b'\x03\xc4\x85v\x00\x00\x00\x00'
    
    	    def ashex(s):
    	>       return s.encode('hex')
    	E       AttributeError: 'bytes' object has no attribute 'encode'
    
    	zodbtools/util.py:29: AttributeError
    
    s.encode('hex') used to work on Py2 but fails on Py3:
    
    	In [1]: s = "abc"
    
    	In [2]: b = b"def"
    
    	In [3]: s.encode('hex')
    	---------------------------------------------------------------------------
    	LookupError                               Traceback (most recent call last)
    	<ipython-input-3-75ae843597fe> in <module>()
    	----> 1 s.encode('hex')
    
    	LookupError: 'hex' is not a text encoding; use codecs.encode() to handle arbitrary codecs
    
    	In [4]: b.encode('hex')
    	---------------------------------------------------------------------------
    	AttributeError                            Traceback (most recent call last)
    	<ipython-input-4-ec2fccff20bc> in <module>()
    	----> 1 b.encode('hex')
    
    	AttributeError: 'bytes' object has no attribute 'encode'
    
    	In [5]: import codecs
    
    	In [6]: codecs.encode(b, 'hex')
    	Out[6]: b'646566'
    
    	In [7]: codecs.encode(s, 'hex')
    	---------------------------------------------------------------------------
    	TypeError                                 Traceback (most recent call last)
    	/usr/lib/python3.7/encodings/hex_codec.py in hex_encode(input, errors)
    	     14     assert errors == 'strict'
    	---> 15     return (binascii.b2a_hex(input), len(input))
    	     16
    
    	TypeError: a bytes-like object is required, not 'str'
    
    	The above exception was the direct cause of the following exception:
    
    	TypeError                                 Traceback (most recent call last)
    	<ipython-input-7-7fcb16cead4f> in <module>()
    	----> 1 codecs.encode(s, 'hex')
    
    	TypeError: encoding with 'hex' codec failed (TypeError: a bytes-like object is required, not 'str')
    
    After the patch it works with bytes and raises for str.
    Fromhex does not need to be changed - it already uses codecs.decode way as
    originally added in dd959b28 (zodbdump += DumpReader - to read/parse zodbdump
    stream).
    
    Based on patch by Jérome Perrin.
    7a7370e6
util.py 6.09 KB