From 55c96e8053689c29ae28a9d2117ae37934eace68 Mon Sep 17 00:00:00 2001 From: NewUserHa <32261870+NewUserHa@users.noreply.github.com> Date: Sat, 12 Nov 2022 06:45:24 +0800 Subject: [PATCH] gh-99305: Speed up secrets.token_hex() ~2x (#99306) simple code modernization. Co-authored-by: Pieter Eendebak --- Lib/secrets.py | 3 +-- .../next/Library/2022-11-10-11-51-39.gh-issue-99305.6LzQc3.rst | 1 + 2 files changed, 2 insertions(+), 2 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2022-11-10-11-51-39.gh-issue-99305.6LzQc3.rst diff --git a/Lib/secrets.py b/Lib/secrets.py index 900381a89f5..566a09b7311 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. diff --git a/Misc/NEWS.d/next/Library/2022-11-10-11-51-39.gh-issue-99305.6LzQc3.rst b/Misc/NEWS.d/next/Library/2022-11-10-11-51-39.gh-issue-99305.6LzQc3.rst new file mode 100644 index 00000000000..32e18e5d4a4 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2022-11-10-11-51-39.gh-issue-99305.6LzQc3.rst @@ -0,0 +1 @@ +Improve performance of :func:`secrets.token_hex`.