summaryrefslogtreecommitdiff
path: root/passlib/utils
diff options
context:
space:
mode:
authorEli Collins <elic@assurancetechnologies.com>2020-10-06 14:13:33 -0400
committerEli Collins <elic@assurancetechnologies.com>2020-10-06 14:13:33 -0400
commit65f4a25efd41639552df52dba40bfc377ae00871 (patch)
tree363bf55e05d7484d8b407e58fa2526719138b201 /passlib/utils
parentcc1c32da8866bdcc65bee916cd202f660b0cd88e (diff)
downloadpasslib-65f4a25efd41639552df52dba40bfc377ae00871.tar.gz
cleanup old python compat -- removed PY2 & PY3 conditionals
Diffstat (limited to 'passlib/utils')
-rw-r--r--passlib/utils/__init__.py112
-rw-r--r--passlib/utils/binary.py20
-rw-r--r--passlib/utils/compat/__init__.py114
-rw-r--r--passlib/utils/decor.py13
-rw-r--r--passlib/utils/handlers.py4
5 files changed, 63 insertions, 200 deletions
diff --git a/passlib/utils/__init__.py b/passlib/utils/__init__.py
index 0c950ba..e25d861 100644
--- a/passlib/utils/__init__.py
+++ b/passlib/utils/__init__.py
@@ -62,7 +62,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, irange, imap, PY3,
+ join_byte_elems, irange, imap,
join_unicode, unicode, byte_elem_value, nextgetter,
unicode_or_str, unicode_or_bytes_types,
get_method_function, suppress_cause, PYPY)
@@ -113,7 +113,7 @@ __all__ = [
#=============================================================================
# bitsize of system architecture (32 or 64)
-sys_bits = int(math.log(sys.maxsize if PY3 else sys.maxint, 2) + 1.5)
+sys_bits = int(math.log(sys.maxsize, 2) + 1.5)
# list of hashes algs supported by crypt() on at least one OS.
# XXX: move to .registry for passlib 2.0?
@@ -166,30 +166,23 @@ class SequenceMixin(object):
def __ne__(self, other):
return not self.__eq__(other)
-if PY3:
- # getargspec() is deprecated, use this under py3.
- # even though it's a lot more awkward to get basic info :|
+# getargspec() is deprecated, use this under py3.
+# even though it's a lot more awkward to get basic info :|
- _VAR_KEYWORD = inspect.Parameter.VAR_KEYWORD
- _VAR_ANY_SET = set([_VAR_KEYWORD, inspect.Parameter.VAR_POSITIONAL])
+_VAR_KEYWORD = inspect.Parameter.VAR_KEYWORD
+_VAR_ANY_SET = {_VAR_KEYWORD, inspect.Parameter.VAR_POSITIONAL}
- def accepts_keyword(func, key):
- """test if function accepts specified keyword"""
- params = inspect.signature(get_method_function(func)).parameters
- if not params:
- return False
- arg = params.get(key)
- if arg and arg.kind not in _VAR_ANY_SET:
- return True
- # XXX: annoying what we have to do to determine if VAR_KWDS in use.
- return params[list(params)[-1]].kind == _VAR_KEYWORD
-
-else:
+def accepts_keyword(func, key):
+ """test if function accepts specified keyword"""
+ params = inspect.signature(get_method_function(func)).parameters
+ if not params:
+ return False
+ arg = params.get(key)
+ if arg and arg.kind not in _VAR_ANY_SET:
+ return True
+ # XXX: annoying what we have to do to determine if VAR_KWDS in use.
+ return params[list(params)[-1]].kind == _VAR_KEYWORD
- def accepts_keyword(func, key):
- """test if function accepts specified keyword"""
- spec = inspect.getargspec(get_method_function(func))
- return key in spec.args or spec.keywords is not None
def update_mixin_classes(target, add=None, remove=None, append=False,
before=None, after=None, dryrun=False):
@@ -333,11 +326,11 @@ def consteq(left, right):
if isinstance(left, unicode):
if not isinstance(right, unicode):
raise TypeError("inputs must be both unicode or both bytes")
- is_py3_bytes = False
+ is_bytes = False
elif isinstance(left, bytes):
if not isinstance(right, bytes):
raise TypeError("inputs must be both unicode or both bytes")
- is_py3_bytes = PY3
+ is_bytes = True
else:
raise TypeError("inputs must be both unicode or both bytes")
@@ -359,7 +352,7 @@ def consteq(left, right):
# run constant-time string comparision
# TODO: use izip instead (but first verify it's faster than zip for this case)
- if is_py3_bytes:
+ if is_bytes:
for l,r in zip(tmp, right):
result |= l ^ r
else:
@@ -554,19 +547,11 @@ def render_bytes(source, *args):
else arg for arg in args)
return result.encode("latin-1")
-if PY3:
- # new in py32
- def bytes_to_int(value):
- return int.from_bytes(value, 'big')
- def int_to_bytes(value, count):
- return value.to_bytes(count, 'big')
-else:
- # XXX: can any of these be sped up?
- from binascii import hexlify, unhexlify
- def bytes_to_int(value):
- return int(hexlify(value),16)
- def int_to_bytes(value, count):
- return unhexlify(('%%0%dx' % (count<<1)) % value)
+def bytes_to_int(value):
+ return int.from_bytes(value, 'big')
+
+def int_to_bytes(value, count):
+ return value.to_bytes(count, 'big')
add_doc(bytes_to_int, "decode byte string as single big-endian integer")
add_doc(int_to_bytes, "encode integer as single big-endian byte string")
@@ -760,22 +745,15 @@ def to_unicode(source, encoding="utf-8", param="value"):
else:
raise ExpectedStringError(source, param)
-if PY3:
- def to_native_str(source, encoding="utf-8", param="value"):
- if isinstance(source, bytes):
- return source.decode(encoding)
- elif isinstance(source, unicode):
- return source
- else:
- raise ExpectedStringError(source, param)
-else:
- def to_native_str(source, encoding="utf-8", param="value"):
- if isinstance(source, bytes):
- return source
- elif isinstance(source, unicode):
- return source.encode(encoding)
- else:
- raise ExpectedStringError(source, param)
+
+def to_native_str(source, encoding="utf-8", param="value"):
+ if isinstance(source, bytes):
+ return source.decode(encoding)
+ elif isinstance(source, unicode):
+ return source
+ else:
+ raise ExpectedStringError(source, param)
+
add_doc(to_native_str,
"""Take in unicode or bytes, return native string.
@@ -837,7 +815,7 @@ def is_safe_crypt_input(value):
"""
UT helper --
test if value is safe to pass to crypt.crypt();
- under PY3, can't pass non-UTF8 bytes to crypt.crypt.
+ since PY3 won't let us pass non-UTF8 bytes to crypt.crypt.
"""
if crypt_accepts_bytes or not isinstance(value, bytes):
return True
@@ -882,7 +860,7 @@ else:
# chars in this string...
_invalid_prefixes = u"*:!"
- if PY3:
+ if True: # legacy block from PY3 compat
# * pypy3 (as of v7.3.1) has a crypt which accepts bytes, or ASCII-only unicode.
# * whereas CPython3 (as of v3.9) has a crypt which doesn't take bytes,
@@ -942,27 +920,7 @@ else:
if not result or result[0] in _invalid_prefixes:
return None
return result
- else:
-
- #: see feature-detection in PY3 fork above
- crypt_accepts_bytes = True
- # Python 2 crypt handler
- def safe_crypt(secret, hash):
- if isinstance(secret, unicode):
- secret = secret.encode("utf-8")
- if _NULL in secret:
- raise ValueError("null character in secret")
- if isinstance(hash, unicode):
- hash = hash.encode("ascii")
- with _safe_crypt_lock:
- result = _crypt(secret, hash)
- if not result:
- return None
- result = result.decode("ascii")
- if result[0] in _invalid_prefixes:
- return None
- return result
add_doc(safe_crypt, """Wrapper around stdlib's crypt.
diff --git a/passlib/utils/binary.py b/passlib/utils/binary.py
index 101cbe8..bdef73b 100644
--- a/passlib/utils/binary.py
+++ b/passlib/utils/binary.py
@@ -18,7 +18,7 @@ log = logging.getLogger(__name__)
# pkg
from passlib import exc
from passlib.utils.compat import (
- PY3, bascii_to_str,
+ bascii_to_str,
irange, imap, iter_byte_chars, join_byte_values, join_byte_elems,
nextgetter, suppress_cause,
unicode, unicode_or_bytes_types,
@@ -384,10 +384,7 @@ class Base64Engine(object):
if not isinstance(source, bytes):
raise TypeError("source must be bytes, not %s" % (type(source),))
chunks, tail = divmod(len(source), 3)
- if PY3:
- next_value = nextgetter(iter(source))
- else:
- next_value = nextgetter(ord(elem) for elem in source)
+ next_value = nextgetter(iter(source))
gen = self._encode_bytes(next_value, chunks, tail)
out = join_byte_elems(imap(self._encode64, gen))
##if tail:
@@ -634,8 +631,7 @@ class Base64Engine(object):
# all chars used by encoding are 7-bit ascii.
last = self._encode64(self._decode64(last) & mask)
assert last in padset, "failed to generate valid padding char"
- if PY3:
- last = bytes([last])
+ last = bytes([last])
return True, source[:-1] + last
def repair_unused(self, source):
@@ -723,9 +719,8 @@ class Base64Engine(object):
raise TypeError("source must be bytes, not %s" % (type(source),))
if len(source) != 1:
raise ValueError("source must be exactly 1 byte")
- if PY3:
- # convert to 8bit int before doing lookup
- source = source[0]
+ # convert to 8bit int before doing lookup
+ source = source[0]
try:
return self._decode64(source)
except KeyError:
@@ -808,10 +803,7 @@ class Base64Engine(object):
"""encodes 6-bit integer -> single hash64 character"""
if value < 0 or value > 63:
raise ValueError("value out of range")
- if PY3:
- return self.bytemap[value:value+1]
- else:
- return self._encode64(value)
+ return self.bytemap[value:value+1]
def encode_int12(self, value):
"""encodes 12-bit integer -> 2 char string"""
diff --git a/passlib/utils/compat/__init__.py b/passlib/utils/compat/__init__.py
index 9e58d58..2ad834e 100644
--- a/passlib/utils/compat/__init__.py
+++ b/passlib/utils/compat/__init__.py
@@ -7,8 +7,6 @@
# python version
#------------------------------------------------------------------------
import sys
-PY2 = sys.version_info < (3,0)
-PY3 = sys.version_info >= (3,0)
# make sure it's not an unsupported version, even if we somehow got this far
if sys.version_info < (3, 5):
@@ -32,10 +30,7 @@ PYSTON = "Pyston" in sys.version
# common imports
#=============================================================================
import logging; log = logging.getLogger(__name__)
-if PY3:
- import builtins
-else:
- import __builtin__ as builtins
+import builtins
def add_doc(obj, doc):
"""add docstring to an object"""
@@ -45,9 +40,6 @@ def add_doc(obj, doc):
# the default exported vars
#=============================================================================
__all__ = [
- # python versions
- 'PY2', 'PY3',
-
# io
'BytesIO', 'StringIO', 'NativeStringIO', 'SafeConfigParser',
@@ -91,7 +83,8 @@ _lazy_attrs = dict()
#=============================================================================
# unicode & bytes types
#=============================================================================
-if PY3:
+
+if True: # legacy PY3 indent
unicode = str
# NOTE: don't need to use this for general u'xxx' case,
@@ -103,15 +96,6 @@ if PY3:
unicode_or_bytes_types = (str, bytes)
native_string_types = (unicode,)
-else:
- unicode = builtins.unicode
-
- def u(s):
- assert isinstance(s, str)
- return s.decode("ascii")
-
- unicode_or_bytes_types = (basestring,)
- native_string_types = (basestring,)
# shorter preferred aliases
# TODO: align compat module w/ crowbar.compat naming
@@ -132,7 +116,7 @@ join_unicode = u''.join
# function to join list of byte strings
join_bytes = b''.join
-if PY3:
+if True: # legacy PY3 indent
def uascii_to_str(s):
assert isinstance(s, unicode)
return s
@@ -164,38 +148,7 @@ if PY3:
# FIXME: there has to be a better way to do this
return (bytes([c]) for c in s)
-else:
- def uascii_to_str(s):
- assert isinstance(s, unicode)
- return s.encode("ascii")
-
- def bascii_to_str(s):
- assert isinstance(s, bytes)
- return s
-
- def str_to_uascii(s):
- assert isinstance(s, str)
- return s.decode("ascii")
-
- def str_to_bascii(s):
- assert isinstance(s, str)
- return s
-
- def join_byte_values(values):
- return join_bytes(chr(v) for v in values)
-
- join_byte_elems = join_bytes
-
- byte_elem_value = ord
-
- def iter_byte_values(s):
- assert isinstance(s, bytes)
- return (ord(c) for c in s)
-
- def iter_byte_chars(s):
- assert isinstance(s, bytes)
- return s
-
+# TODO: move docstrings to funcs...
add_doc(uascii_to_str, "helper to convert ascii unicode -> native str")
add_doc(bascii_to_str, "helper to convert ascii bytes -> native str")
add_doc(str_to_uascii, "helper to convert ascii native str -> unicode")
@@ -205,7 +158,7 @@ add_doc(str_to_bascii, "helper to convert ascii native str -> bytes")
# join_byte_elems -- function to convert list of byte elements to byte string;
# i.e. what's returned by ``b('a')[0]``...
-# this is b('a') under PY2, but 97 under PY3.
+# this is 97 under PY3.
# byte_elem_value -- function to convert byte element to integer -- a noop under PY3
@@ -215,12 +168,9 @@ add_doc(iter_byte_chars, "iterate over byte string as sequence of 1-byte strings
#=============================================================================
# numeric
#=============================================================================
-if PY3:
- int_types = (int,)
- num_types = (int, float)
-else:
- int_types = (int, long)
- num_types = (int, long, float)
+
+int_types = (int,)
+num_types = (int, float)
#=============================================================================
# iteration helpers
@@ -231,7 +181,7 @@ else:
# imap - map to iterator
# lmap - map to list
#=============================================================================
-if PY3:
+if True: # legacy PY3 indent
irange = range
##def lrange(*a,**k):
## return list(range(*a,**k))
@@ -250,21 +200,6 @@ if PY3:
izip = zip
-else:
- irange = xrange
- ##lrange = range
-
- lmap = map
- from itertools import imap, izip
-
- def iteritems(d):
- return d.iteritems()
- def itervalues(d):
- return d.itervalues()
-
- def nextgetter(obj):
- return obj.next
-
add_doc(nextgetter, "return function that yields successive values from iterable")
#=============================================================================
@@ -277,10 +212,7 @@ add_doc(nextgetter, "return function that yields successive values from iterable
#=============================================================================
# introspection
#=============================================================================
-if PY3:
- method_function_attr = "__func__"
-else:
- method_function_attr = "im_func"
+method_function_attr = "__func__"
def get_method_function(func):
"""given (potential) method, return underlying function"""
@@ -288,7 +220,7 @@ def get_method_function(func):
def get_unbound_method_function(func):
"""given unbound method, return underlying function"""
- return func if PY3 else func.__func__
+ return func
def error_from(exc, # *,
cause=None):
@@ -307,21 +239,13 @@ suppress_cause = error_from
#=============================================================================
# input/output
#=============================================================================
-if PY3:
- _lazy_attrs = dict(
- BytesIO="io.BytesIO",
- UnicodeIO="io.StringIO",
- NativeStringIO="io.StringIO",
- SafeConfigParser="configparser.ConfigParser",
- )
-
-else:
- _lazy_attrs = dict(
- BytesIO="cStringIO.StringIO",
- UnicodeIO="StringIO.StringIO",
- NativeStringIO="cStringIO.StringIO",
- SafeConfigParser="ConfigParser.SafeConfigParser",
- )
+
+_lazy_attrs = dict(
+ BytesIO="io.BytesIO",
+ UnicodeIO="io.StringIO",
+ NativeStringIO="io.StringIO",
+ SafeConfigParser="configparser.ConfigParser",
+)
#=============================================================================
# collections
diff --git a/passlib/utils/decor.py b/passlib/utils/decor.py
index 392e569..bd4c290 100644
--- a/passlib/utils/decor.py
+++ b/passlib/utils/decor.py
@@ -12,7 +12,6 @@ import types
from warnings import warn
# site
# pkg
-from passlib.utils.compat import PY3
# local
__all__ = [
"classproperty",
@@ -55,10 +54,7 @@ class hybrid_method(object):
def __get__(self, obj, cls):
if obj is None:
obj = cls
- if PY3:
- return types.MethodType(self.func, obj)
- else:
- return types.MethodType(self.func, obj, cls)
+ return types.MethodType(self.func, obj)
#=============================================================================
# memoization
@@ -103,13 +99,6 @@ class memoized_property(object):
setattr(obj, self.__name__, value)
return value
- if not PY3:
-
- @property
- def im_func(self):
- """py2 alias"""
- return self.__func__
-
def clear_cache(self, obj):
"""
class-level helper to clear stored value (if any).
diff --git a/passlib/utils/handlers.py b/passlib/utils/handlers.py
index 6115d11..8034cc3 100644
--- a/passlib/utils/handlers.py
+++ b/passlib/utils/handlers.py
@@ -28,7 +28,7 @@ from passlib.utils.binary import (
)
from passlib.utils.compat import join_byte_values, irange, native_string_types, \
uascii_to_str, join_unicode, unicode, str_to_uascii, \
- join_unicode, unicode_or_bytes_types, PY2, int_types
+ join_unicode, unicode_or_bytes_types, int_types
from passlib.utils.decor import classproperty, deprecated_method
# local
__all__ = [
@@ -1408,7 +1408,7 @@ class HasSalt(GenericHandler):
else:
if not isinstance(salt, unicode):
# NOTE: allowing bytes under py2 so salt can be native str.
- if isinstance(salt, bytes) and (PY2 or relaxed):
+ if relaxed and isinstance(salt, bytes):
salt = salt.decode("ascii")
else:
raise exc.ExpectedTypeError(salt, "unicode", "salt")