summaryrefslogtreecommitdiff
path: root/passlib/utils
diff options
context:
space:
mode:
authorEli Collins <elic@assurancetechnologies.com>2020-10-06 15:08:56 -0400
committerEli Collins <elic@assurancetechnologies.com>2020-10-06 15:08:56 -0400
commit3709566d41523e5bc31e1063b647e90f1469744a (patch)
treee29eed3fa76fad9373432cda397ff7dc9cb24e4e /passlib/utils
parent56017e683f8e31be252c94f23d4dd22a2d5603f9 (diff)
downloadpasslib-3709566d41523e5bc31e1063b647e90f1469744a.tar.gz
cleanup old python compat -- replaced "unicode" alias in favor of "str"
Diffstat (limited to 'passlib/utils')
-rw-r--r--passlib/utils/__init__.py39
-rw-r--r--passlib/utils/binary.py14
-rw-r--r--passlib/utils/compat/__init__.py4
-rw-r--r--passlib/utils/handlers.py37
4 files changed, 45 insertions, 49 deletions
diff --git a/passlib/utils/__init__.py b/passlib/utils/__init__.py
index b06ba57..e5ff515 100644
--- a/passlib/utils/__init__.py
+++ b/passlib/utils/__init__.py
@@ -63,7 +63,7 @@ from passlib.utils.decor import (
from passlib.exc import ExpectedStringError, ExpectedTypeError
from passlib.utils.compat import (add_doc, join_bytes, join_byte_values,
join_byte_elems,
- join_unicode, unicode, byte_elem_value,
+ join_unicode, byte_elem_value,
unicode_or_bytes,
get_method_function, PYPY)
# local
@@ -323,16 +323,16 @@ def consteq(left, right):
# http://bugs.python.org/issue14955
# validate types
- if isinstance(left, unicode):
- if not isinstance(right, unicode):
- raise TypeError("inputs must be both unicode or both bytes")
+ if isinstance(left, str):
+ if not isinstance(right, str):
+ raise TypeError("inputs must be both str or both bytes")
is_bytes = False
elif isinstance(left, bytes):
if not isinstance(right, bytes):
- raise TypeError("inputs must be both unicode or both bytes")
+ raise TypeError("inputs must be both str or both bytes")
is_bytes = True
else:
- raise TypeError("inputs must be both unicode or both bytes")
+ raise TypeError("inputs must be both str or both bytes")
# do size comparison.
# NOTE: the double-if construction below is done deliberately, to ensure
@@ -431,8 +431,8 @@ def saslprep(source, param="value"):
# validate type
# XXX: support bytes (e.g. run through want_unicode)?
# might be easier to just integrate this into cryptcontext.
- if not isinstance(source, unicode):
- raise TypeError("input must be unicode string, not %s" %
+ if not isinstance(source, str):
+ raise TypeError("input must be string, not %s" %
(type(source),))
# mapping stage
@@ -583,7 +583,7 @@ def right_pad_string(source, size, pad=None):
cur = len(source)
if size > cur:
if pad is None:
- pad = _UNULL if isinstance(source, unicode) else _BNULL
+ pad = _UNULL if isinstance(source, str) else _BNULL
return source+pad*(size-cur)
else:
return source[:size]
@@ -698,7 +698,7 @@ def to_bytes(source, encoding="utf-8", param="value", source_encoding=None):
the source will be transcoded from *source_encoding* to *encoding*
(via unicode).
- :raises TypeError: if source is not unicode or bytes.
+ :raises TypeError: if source is not str or bytes.
:returns:
* unicode strings will be encoded using *encoding*, and returned.
@@ -713,7 +713,7 @@ def to_bytes(source, encoding="utf-8", param="value", source_encoding=None):
return source.decode(source_encoding).encode(encoding)
else:
return source
- elif isinstance(source, unicode):
+ elif isinstance(source, str):
return source.encode(encoding)
else:
raise ExpectedStringError(source, param)
@@ -730,14 +730,14 @@ def to_unicode(source, encoding="utf-8", param="value"):
:param param:
optional name of variable/noun to reference when raising errors.
- :raises TypeError: if source is not unicode or bytes.
+ :raises TypeError: if source is not str or bytes.
:returns:
* returns unicode strings unchanged.
* returns bytes strings decoded using *encoding*
"""
assert encoding
- if isinstance(source, unicode):
+ if isinstance(source, str):
return source
elif isinstance(source, bytes):
return source.decode(encoding)
@@ -748,17 +748,16 @@ def to_unicode(source, encoding="utf-8", param="value"):
def to_native_str(source, encoding="utf-8", param="value"):
if isinstance(source, bytes):
return source.decode(encoding)
- elif isinstance(source, unicode):
+ elif isinstance(source, str):
return source
else:
raise ExpectedStringError(source, param)
add_doc(to_native_str,
- """Take in unicode or bytes, return native string.
+ """Take in str or bytes, returns str.
- Python 2: encodes unicode using specified encoding, leaves bytes alone.
- Python 3: leaves unicode alone, decodes bytes using specified encoding.
+ leaves str alone, decodes bytes using specified encoding.
:raises TypeError: if source is not unicode or bytes.
@@ -879,11 +878,11 @@ else:
if crypt_accepts_bytes:
# PyPy3 -- all bytes accepted, but unicode encoded to ASCII,
# so handling that ourselves.
- if isinstance(secret, unicode):
+ if isinstance(secret, str):
secret = secret.encode("utf-8")
if _BNULL in secret:
raise ValueError("null character in secret")
- if isinstance(hash, unicode):
+ if isinstance(hash, str):
hash = hash.encode("ascii")
else:
# CPython3's crypt() doesn't take bytes, only unicode; unicode which is then
@@ -1086,7 +1085,7 @@ def getrandstr(rng, charset, count):
value //= letters
i += 1
- if isinstance(charset, unicode):
+ if isinstance(charset, str):
return join_unicode(helper())
else:
return join_byte_elems(helper())
diff --git a/passlib/utils/binary.py b/passlib/utils/binary.py
index 5c55477..37bfefa 100644
--- a/passlib/utils/binary.py
+++ b/passlib/utils/binary.py
@@ -20,7 +20,7 @@ from passlib import exc
from passlib.utils.compat import (
bascii_to_str,
iter_byte_chars, join_byte_values, join_byte_elems,
- unicode, unicode_or_bytes,
+ unicode_or_bytes,
)
from passlib.utils.decor import memoized_property
# from passlib.utils import BASE64_CHARS, HASH64_CHARS
@@ -129,7 +129,7 @@ def compile_byte_translation(mapping, source=None):
if isinstance(k, unicode_or_bytes):
k = ord(k)
assert isinstance(k, int) and 0 <= k < 256
- if isinstance(v, unicode):
+ if isinstance(v, str):
v = v.encode("ascii")
assert isinstance(v, bytes) and len(v) == 1
target[k] = v
@@ -150,7 +150,7 @@ def b64s_decode(data):
decode from shortened base64 format which omits padding & whitespace.
uses default ``+/`` altchars.
"""
- if isinstance(data, unicode):
+ if isinstance(data, str):
# needs bytes for replace() call, but want to accept ascii-unicode ala a2b_base64()
try:
data = data.encode("ascii")
@@ -196,7 +196,7 @@ def ab64_decode(data):
it is primarily used by Passlib's custom pbkdf2 hashes.
"""
- if isinstance(data, unicode):
+ if isinstance(data, str):
# needs bytes for replace() call, but want to accept ascii-unicode ala a2b_base64()
try:
data = data.encode("ascii")
@@ -231,7 +231,7 @@ def b32decode(source):
padding optional, ignored if present.
"""
# encode & correct for typos
- if isinstance(source, unicode):
+ if isinstance(source, str):
source = source.encode("ascii")
source = source.translate(_b32_translate)
@@ -334,7 +334,7 @@ class Base64Engine(object):
#===================================================================
def __init__(self, charmap, big=False):
# validate charmap, generate encode64/decode64 helper functions.
- if isinstance(charmap, unicode):
+ if isinstance(charmap, str):
charmap = charmap.encode("latin-1")
elif not isinstance(charmap, bytes):
raise exc.ExpectedStringError(charmap, "charmap")
@@ -621,7 +621,7 @@ class Base64Engine(object):
# we have dirty bits - repair the string by decoding last char,
# clearing the padding bits via <mask>, and encoding new char.
- if isinstance(source, unicode):
+ if isinstance(source, str):
cm = self.charmap
last = cm[cm.index(last) & mask]
assert last in padset, "failed to generate valid padding char"
diff --git a/passlib/utils/compat/__init__.py b/passlib/utils/compat/__init__.py
index 5ecb3e2..f81c6ad 100644
--- a/passlib/utils/compat/__init__.py
+++ b/passlib/utils/compat/__init__.py
@@ -44,7 +44,6 @@ __all__ = [
# unicode/bytes types & helpers
'u',
- 'unicode',
'uascii_to_str', 'bascii_to_str',
'str_to_uascii', 'str_to_bascii',
'join_unicode', 'join_bytes',
@@ -68,7 +67,6 @@ _lazy_attrs = dict()
#=============================================================================
if True: # legacy PY3 indent
- unicode = str
# NOTE: don't need to use this for general u'xxx' case,
# but DO need it as wrapper for u(r'xxx') case (mainly when compiling regexen)
@@ -90,7 +88,7 @@ join_bytes = b''.join
if True: # legacy PY3 indent
def uascii_to_str(s):
- assert isinstance(s, unicode)
+ assert isinstance(s, str)
return s
def bascii_to_str(s):
diff --git a/passlib/utils/handlers.py b/passlib/utils/handlers.py
index fbdc22e..c5b0bf9 100644
--- a/passlib/utils/handlers.py
+++ b/passlib/utils/handlers.py
@@ -27,7 +27,7 @@ from passlib.utils.binary import (
ALL_BYTE_VALUES,
)
from passlib.utils.compat import join_byte_values, \
- uascii_to_str, join_unicode, unicode, str_to_uascii, \
+ uascii_to_str, join_unicode, str_to_uascii, \
join_unicode, unicode_or_bytes, int_types
from passlib.utils.decor import classproperty, deprecated_method
# local
@@ -124,7 +124,7 @@ def validate_secret(secret):
def to_unicode_for_identify(hash):
"""convert hash to unicode for identify method"""
- if isinstance(hash, unicode):
+ if isinstance(hash, str):
return hash
elif isinstance(hash, bytes):
# try as utf-8, but if it fails, use foolproof latin-1,
@@ -143,8 +143,8 @@ def parse_mc2(hash, prefix, sep=_UDOLLAR, handler=None):
this expects a hash of the format :samp:`{prefix}{salt}[${checksum}]`,
such as md5_crypt, and parses it into salt / checksum portions.
- :arg hash: the hash to parse (bytes or unicode)
- :arg prefix: the identifying prefix (unicode)
+ :arg hash: the hash to parse (bytes or str)
+ :arg prefix: the identifying prefix (str)
:param sep: field separator (unicode, defaults to ``$``).
:param handler: handler class to pass to error constructors.
@@ -153,12 +153,12 @@ def parse_mc2(hash, prefix, sep=_UDOLLAR, handler=None):
"""
# detect prefix
hash = to_unicode(hash, "ascii", "hash")
- assert isinstance(prefix, unicode)
+ assert isinstance(prefix, str)
if not hash.startswith(prefix):
raise exc.InvalidHashError(handler)
# parse 2-part hash or 1-part config string
- assert isinstance(sep, unicode)
+ assert isinstance(sep, str)
parts = hash[len(prefix):].split(sep)
if len(parts) == 2:
salt, chk = parts
@@ -192,12 +192,12 @@ def parse_mc3(hash, prefix, sep=_UDOLLAR, rounds_base=10,
"""
# detect prefix
hash = to_unicode(hash, "ascii", "hash")
- assert isinstance(prefix, unicode)
+ assert isinstance(prefix, str)
if not hash.startswith(prefix):
raise exc.InvalidHashError(handler)
# parse 3-part hash or 2-part config string
- assert isinstance(sep, unicode)
+ assert isinstance(sep, str)
parts = hash[len(prefix):].split(sep)
if len(parts) == 3:
rounds, salt, chk = parts
@@ -307,7 +307,7 @@ def render_mc3(ident, rounds, salt, checksum, sep=u"$", rounds_base=10):
rounds = u"%x" % rounds
else:
assert rounds_base == 10
- rounds = unicode(rounds)
+ rounds = str(rounds)
if checksum:
parts = [ident, rounds, sep, salt, sep, checksum]
else:
@@ -335,12 +335,12 @@ def mask_value(value, show=4, pct=0.125, char=u"*"):
"""
if value is None:
return None
- if not isinstance(value, unicode):
+ if not isinstance(value, str):
if isinstance(value, bytes):
from passlib.utils.binary import ab64_encode
value = ab64_encode(value).decode("ascii")
else:
- value = unicode(value)
+ value = str(value)
size = len(value)
show = min(show, int(size * pct))
return value[:show] + char * (size - show)
@@ -640,12 +640,12 @@ class GenericHandler(MinimalHandler):
if not isinstance(checksum, bytes):
raise exc.ExpectedTypeError(checksum, "bytes", "checksum")
- elif not isinstance(checksum, unicode):
+ elif not isinstance(checksum, str):
if isinstance(checksum, bytes) and relaxed:
warn("checksum should be unicode, not bytes", PasslibHashWarning)
checksum = checksum.decode("ascii")
else:
- raise exc.ExpectedTypeError(checksum, "unicode", "checksum")
+ raise exc.ExpectedTypeError(checksum, "str", "checksum")
# check size
cc = self.checksum_size
@@ -712,8 +712,7 @@ class GenericHandler(MinimalHandler):
:returns:
hash string with salt & digest included.
- should return native string type (ascii-bytes under python 2,
- unicode under python 3)
+ should return native str.
"""
raise NotImplementedError("%s must implement from_string()" % (self.__class__,))
@@ -751,7 +750,7 @@ class GenericHandler(MinimalHandler):
string, taking config from object state
calc checksum implementations may assume secret is always
- either unicode or bytes, checks are performed by verify/etc.
+ either str or bytes, checks are performed by verify/etc.
"""
raise NotImplementedError("%s must implement _calc_checksum()" %
(self.__class__,))
@@ -1057,7 +1056,7 @@ class HasManyIdents(GenericHandler):
#===================================================================
# class attrs
#===================================================================
- default_ident = None # should be unicode
+ default_ident = None # should be str
ident_values = None # should be list of unicode strings
ident_aliases = None # should be dict of unicode -> unicode
# NOTE: any aliases provided to norm_ident() as bytes
@@ -1406,12 +1405,12 @@ class HasSalt(GenericHandler):
if not isinstance(salt, bytes):
raise exc.ExpectedTypeError(salt, "bytes", "salt")
else:
- if not isinstance(salt, unicode):
+ if not isinstance(salt, str):
# NOTE: allowing bytes under py2 so salt can be native str.
if relaxed and isinstance(salt, bytes):
salt = salt.decode("ascii")
else:
- raise exc.ExpectedTypeError(salt, "unicode", "salt")
+ raise exc.ExpectedTypeError(salt, "str", "salt")
# check charset
sc = cls.salt_chars