This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Small Refactoring: Use bytes.hex() in secrets.token_hex()
Type: performance Stage: resolved
Components: Library (Lib) Versions: Python 3.9
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: Dennis Sweeney, steven.daprano
Priority: normal Keywords: patch

Created on 2020-04-28 06:55 by Dennis Sweeney, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Pull Requests
URL Status Linked Edit
PR 19749 closed Dennis Sweeney, 2020-04-28 06:56
Messages (1)
msg367502 - (view) Author: Dennis Sweeney (Dennis Sweeney) * (Python committer) Date: 2020-04-28 06:55
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?
History
Date User Action Args
2022-04-11 14:59:30adminsetgithub: 84598
2021-10-07 02:45:40Dennis Sweeneysetstatus: open -> closed
resolution: not a bug
stage: patch review -> resolved
2020-04-28 13:29:25xtreaksetnosy: + steven.daprano
2020-04-28 06:59:37Dennis Sweeneysettitle: Small Refactoring: Use the bytes.hex() in secrets.token_hex() -> Small Refactoring: Use bytes.hex() in secrets.token_hex()
2020-04-28 06:56:12Dennis Sweeneysetkeywords: + patch
stage: patch review
pull_requests: + pull_request19070
2020-04-28 06:55:28Dennis Sweeneycreate