[New-bugs-announce] [issue40418] Small Refactoring: Use the bytes.hex() in secrets.token_hex()
Dennis Sweeney
report at bugs.python.org
Tue Apr 28 02:55:28 EDT 2020
New submission from Dennis Sweeney <sweeney.dennis650 at gmail.com>:
Since bytes.hex() was added in 3.5, we should be able to make the following change:
diff --git a/Lib/secrets.py b/Lib/secrets.py
index a546efbdd4..1dd8629f52 100644
--- a/Lib/secrets.py
+++ b/Lib/secrets.py
@@ -13,7 +13,6 @@ __all__ = ['choice', 'randbelow', 'randbits', 'SystemRandom',
import base64
-import binascii
from hmac import compare_digest
from random import SystemRandom
@@ -56,7 +55,7 @@ def token_hex(nbytes=None):
'f9bf78b9a18ce6d46a0cd2b0b86df9da'
"""
- return binascii.hexlify(token_bytes(nbytes)).decode('ascii')
+ return token_bytes(nbytes).hex()
def token_urlsafe(nbytes=None):
"""Return a random URL-safe text string, in Base64 encoding.
Performance: python -m pyperf timeit -s "from secrets import token_hex" "token_hex(...)"
* token_hex() on master:
Mean +- std dev: 892 ns +- 22 ns
* token_hex() with change:
Mean +- std dev: 750 ns +- 22 ns
* token_hex(1_000_000) on master:
Mean +- std dev: 3.31 ms +- 0.08 ms
* token_hex(1_000_000) with change:
Mean +- std dev: 2.34 ms +- 0.04 ms
Simpler code, better performance. Are there any downsides?
----------
components: Library (Lib)
messages: 367502
nosy: Dennis Sweeney
priority: normal
severity: normal
status: open
title: Small Refactoring: Use the bytes.hex() in secrets.token_hex()
type: performance
versions: Python 3.9
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue40418>
_______________________________________
More information about the New-bugs-announce
mailing list