Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize ensure_str and ensure_binary. #331

Merged
merged 3 commits into from
May 20, 2020
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 14 additions & 7 deletions six.py
Original file line number Diff line number Diff line change
Expand Up @@ -890,10 +890,10 @@ def ensure_binary(s, encoding='utf-8', errors='strict'):
- `str` -> encoded to `bytes`
- `bytes` -> `bytes`
"""
if isinstance(s, text_type):
return s.encode(encoding, errors)
elif isinstance(s, binary_type):
if isinstance(s, binary_type):
return s
elif isinstance(s, text_type):
gpshead marked this conversation as resolved.
Show resolved Hide resolved
return s.encode(encoding, errors)
else:
raise TypeError("not expecting type '%s'" % type(s))

Expand All @@ -909,12 +909,19 @@ def ensure_str(s, encoding='utf-8', errors='strict'):
- `str` -> `str`
- `bytes` -> decoded to `str`
"""
if not isinstance(s, (text_type, binary_type)):
raise TypeError("not expecting type '%s'" % type(s))
# Optimization: fast return for the common case. Improves performance
# by ~2-2.5x in Python 2 or 1.4-1.7x in Py3 for the case where
# s is a str. The uncommon case (unicode in 2, bytes in 3), ends up
# being around the same. The case that suffers is a subclass, or when
# an exception is thrown. Those are about 15-20% slower.
gpshead marked this conversation as resolved.
Show resolved Hide resolved
if type(s) is str:
return s
if PY2 and isinstance(s, text_type):
s = s.encode(encoding, errors)
return s.encode(encoding, errors)
elif PY3 and isinstance(s, binary_type):
s = s.decode(encoding, errors)
return s.decode(encoding, errors)
elif not isinstance(s, (text_type, binary_type)):
raise TypeError("not expecting type '%s'" % type(s))
return s


Expand Down