New submission from Dennis Sweeney <sweeney.dennis...@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 <rep...@bugs.python.org> <https://bugs.python.org/issue40418> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com