Skip to content

Commit 7754262

Browse files
committed
random_hash.py: make code work better with python3
The hashlib algorithms require bytes, as opposed to str. Move the hash computation to bytes to accomodate python3.
1 parent 8d47354 commit 7754262

File tree

1 file changed

+4
-7
lines changed

1 file changed

+4
-7
lines changed

programming/python/random_hash.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
is_py3 = sys.version_info >= (3, ) # XXX: use six package instead.
1414
if is_py3:
1515
CHR_MAX = 0x10FFFF
16-
CONV_FUNC = lambda x: str(chr(x))
16+
CONV_FUNC = lambda x: chr(x).encode()
1717
else:
1818
CHR_MAX = 128
1919
CONV_FUNC = lambda x: chr(x)
@@ -45,12 +45,9 @@ def main():
4545
random.seed()
4646

4747
m = hashlib.sha512()
48-
rand_str = "".join([
49-
CONV_FUNC(random.randrange(CHR_MAX - 1))
50-
for _ in range(args.length)
51-
])
52-
if is_py3: # use six
53-
rand_str = rand_str.encode("utf-8")
48+
rand_str = b"".join(
49+
CONV_FUNC(random.randrange(CHR_MAX - 1)) for _ in range(args.length)
50+
)
5451

5552
m.update(rand_str)
5653
# NB: python 2.x doesn't support `.hexdigest(length)`

0 commit comments

Comments
 (0)