[issue40418] Small Refactoring: Use the bytes.hex() in secrets.token_hex()

2020-04-28 Thread Dennis Sweeney


Change by Dennis Sweeney :


--
keywords: +patch
pull_requests: +19070
stage:  -> patch review
pull_request: https://github.com/python/cpython/pull/19749

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue40418] Small Refactoring: Use the bytes.hex() in secrets.token_hex()

2020-04-28 Thread Dennis Sweeney


New submission from Dennis Sweeney :

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 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com