1
0
mirror of https://github.com/kellyjonbrazil/jc.git synced 2025-07-15 01:24:29 +02:00

Remove redundant Python 2 code (#493)

Co-authored-by: Kelly Brazil <kellyjonbrazil@gmail.com>
This commit is contained in:
Hugo van Kemenade
2023-12-04 23:03:15 +02:00
committed by GitHub
parent d5a8b4eed2
commit 1b1bc46222
14 changed files with 153 additions and 549 deletions

View File

@ -45,10 +45,6 @@ __version_info__ = tuple(int(segment) for segment in __version__.split("."))
import sys
import os
PY3 = sys.version_info[0] == 3
if PY3:
unicode = str
if sys.platform.startswith('java'):
import platform
@ -490,10 +486,7 @@ def _get_win_folder_from_registry(csidl_name):
registry for this guarantees us the correct answer for all CSIDL_*
names.
"""
if PY3:
import winreg as _winreg
else:
import _winreg
shell_folder_name = {
"CSIDL_APPDATA": "AppData",

View File

@ -5,7 +5,7 @@ import socket
import struct
from ._errors import unwrap
from ._types import byte_cls, bytes_to_list, str_cls, type_name
from ._types import type_name
def inet_ntop(address_family, packed_ip):
@ -33,7 +33,7 @@ def inet_ntop(address_family, packed_ip):
repr(address_family)
))
if not isinstance(packed_ip, byte_cls):
if not isinstance(packed_ip, bytes):
raise TypeError(unwrap(
'''
packed_ip must be a byte string, not %s
@ -52,7 +52,7 @@ def inet_ntop(address_family, packed_ip):
))
if address_family == socket.AF_INET:
return '%d.%d.%d.%d' % tuple(bytes_to_list(packed_ip))
return '%d.%d.%d.%d' % tuple(list(packed_ip))
octets = struct.unpack(b'!HHHHHHHH', packed_ip)
@ -106,7 +106,7 @@ def inet_pton(address_family, ip_string):
repr(address_family)
))
if not isinstance(ip_string, str_cls):
if not isinstance(ip_string, str):
raise TypeError(unwrap(
'''
ip_string must be a unicode string, not %s

View File

@ -13,25 +13,16 @@ from __future__ import unicode_literals, division, absolute_import, print_functi
from encodings import idna # noqa
import codecs
import re
import sys
from ._errors import unwrap
from ._types import byte_cls, str_cls, type_name, bytes_to_list, int_types
from ._types import type_name
if sys.version_info < (3,):
from urlparse import urlsplit, urlunsplit
from urllib import (
quote as urlquote,
unquote as unquote_to_bytes,
)
else:
from urllib.parse import (
from urllib.parse import (
quote as urlquote,
unquote_to_bytes,
urlsplit,
urlunsplit,
)
)
def iri_to_uri(value, normalize=False):
@ -48,7 +39,7 @@ def iri_to_uri(value, normalize=False):
A byte string of the ASCII-encoded URI
"""
if not isinstance(value, str_cls):
if not isinstance(value, str):
raise TypeError(unwrap(
'''
value must be a unicode string, not %s
@ -57,18 +48,6 @@ def iri_to_uri(value, normalize=False):
))
scheme = None
# Python 2.6 doesn't split properly is the URL doesn't start with http:// or https://
if sys.version_info < (2, 7) and not value.startswith('http://') and not value.startswith('https://'):
real_prefix = None
prefix_match = re.match('^[^:]*://', value)
if prefix_match:
real_prefix = prefix_match.group(0)
value = 'http://' + value[len(real_prefix):]
parsed = urlsplit(value)
if real_prefix:
value = real_prefix + value[7:]
scheme = _urlquote(real_prefix[:-3])
else:
parsed = urlsplit(value)
if scheme is None:
@ -81,7 +60,7 @@ def iri_to_uri(value, normalize=False):
password = _urlquote(parsed.password, safe='!$&\'()*+,;=')
port = parsed.port
if port is not None:
port = str_cls(port).encode('ascii')
port = str(port).encode('ascii')
netloc = b''
if username is not None:
@ -112,7 +91,7 @@ def iri_to_uri(value, normalize=False):
path = ''
output = urlunsplit((scheme, netloc, path, query, fragment))
if isinstance(output, str_cls):
if isinstance(output, str):
output = output.encode('latin1')
return output
@ -128,7 +107,7 @@ def uri_to_iri(value):
A unicode string of the IRI
"""
if not isinstance(value, byte_cls):
if not isinstance(value, bytes):
raise TypeError(unwrap(
'''
value must be a byte string, not %s
@ -148,7 +127,7 @@ def uri_to_iri(value):
if hostname:
hostname = hostname.decode('idna')
port = parsed.port
if port and not isinstance(port, int_types):
if port and not isinstance(port, int):
port = port.decode('ascii')
netloc = ''
@ -160,7 +139,7 @@ def uri_to_iri(value):
if hostname is not None:
netloc += hostname
if port is not None:
netloc += ':' + str_cls(port)
netloc += ':' + str(port)
path = _urlunquote(parsed.path, remap=['/'], preserve=True)
query = _urlunquote(parsed.query, remap=['&', '='], preserve=True)
@ -182,7 +161,7 @@ def _iri_utf8_errors_handler(exc):
resume at)
"""
bytes_as_ints = bytes_to_list(exc.object[exc.start:exc.end])
bytes_as_ints = list(exc.object[exc.start:exc.end])
replacements = ['%%%02x' % num for num in bytes_as_ints]
return (''.join(replacements), exc.end)
@ -230,7 +209,7 @@ def _urlquote(string, safe=''):
string = re.sub('%[0-9a-fA-F]{2}', _extract_escape, string)
output = urlquote(string.encode('utf-8'), safe=safe.encode('utf-8'))
if not isinstance(output, byte_cls):
if not isinstance(output, bytes):
output = output.encode('ascii')
# Restore the existing quoted values that we extracted

View File

@ -1,135 +0,0 @@
# Copyright (c) 2009 Raymond Hettinger
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
import sys
if not sys.version_info < (2, 7):
from collections import OrderedDict
else:
from UserDict import DictMixin
class OrderedDict(dict, DictMixin):
def __init__(self, *args, **kwds):
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
try:
self.__end
except AttributeError:
self.clear()
self.update(*args, **kwds)
def clear(self):
self.__end = end = []
end += [None, end, end] # sentinel node for doubly linked list
self.__map = {} # key --> [key, prev, next]
dict.clear(self)
def __setitem__(self, key, value):
if key not in self:
end = self.__end
curr = end[1]
curr[2] = end[1] = self.__map[key] = [key, curr, end]
dict.__setitem__(self, key, value)
def __delitem__(self, key):
dict.__delitem__(self, key)
key, prev, next_ = self.__map.pop(key)
prev[2] = next_
next_[1] = prev
def __iter__(self):
end = self.__end
curr = end[2]
while curr is not end:
yield curr[0]
curr = curr[2]
def __reversed__(self):
end = self.__end
curr = end[1]
while curr is not end:
yield curr[0]
curr = curr[1]
def popitem(self, last=True):
if not self:
raise KeyError('dictionary is empty')
if last:
key = reversed(self).next()
else:
key = iter(self).next()
value = self.pop(key)
return key, value
def __reduce__(self):
items = [[k, self[k]] for k in self]
tmp = self.__map, self.__end
del self.__map, self.__end
inst_dict = vars(self).copy()
self.__map, self.__end = tmp
if inst_dict:
return (self.__class__, (items,), inst_dict)
return self.__class__, (items,)
def keys(self):
return list(self)
setdefault = DictMixin.setdefault
update = DictMixin.update
pop = DictMixin.pop
values = DictMixin.values
items = DictMixin.items
iterkeys = DictMixin.iterkeys
itervalues = DictMixin.itervalues
iteritems = DictMixin.iteritems
def __repr__(self):
if not self:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, self.items())
def copy(self):
return self.__class__(self)
@classmethod
def fromkeys(cls, iterable, value=None):
d = cls()
for key in iterable:
d[key] = value
return d
def __eq__(self, other):
if isinstance(other, OrderedDict):
if len(self) != len(other):
return False
for p, q in zip(self.items(), other.items()):
if p != q:
return False
return True
return dict.__eq__(self, other)
def __ne__(self, other):
return not self == other

View File

@ -2,27 +2,9 @@
from __future__ import unicode_literals, division, absolute_import, print_function
import inspect
import sys
if sys.version_info < (3,):
str_cls = unicode # noqa
byte_cls = str
int_types = (int, long) # noqa
def bytes_to_list(byte_string):
return [ord(b) for b in byte_string]
chr_cls = chr
else:
str_cls = str
byte_cls = bytes
int_types = int
bytes_to_list = list
def chr_cls(num):
def chr_cls(num):
return bytes([num])

View File

@ -48,8 +48,10 @@ Other type classes are defined that help compose the types listed above.
from __future__ import unicode_literals, division, absolute_import, print_function
from collections import OrderedDict
from datetime import datetime, timedelta
from fractions import Fraction
from io import BytesIO
import binascii
import copy
import math
@ -58,22 +60,10 @@ import sys
from . import _teletex_codec
from ._errors import unwrap
from ._ordereddict import OrderedDict
from ._types import type_name, str_cls, byte_cls, int_types, chr_cls
from ._types import type_name, chr_cls
from .parser import _parse, _dump_header
from .util import int_to_bytes, int_from_bytes, timezone, extended_datetime, create_timezone, utc_with_dst
if sys.version_info <= (3,):
from cStringIO import StringIO as BytesIO
range = xrange # noqa
_PY2 = True
else:
from io import BytesIO
_PY2 = False
_teletex_codec.register()
@ -220,7 +210,7 @@ class Asn1Value(object):
An instance of the current class
"""
if not isinstance(encoded_data, byte_cls):
if not isinstance(encoded_data, bytes):
raise TypeError('encoded_data must be a byte string, not %s' % type_name(encoded_data))
spec = None
@ -291,7 +281,7 @@ class Asn1Value(object):
cls = self.__class__
# Allow explicit to be specified as a simple 2-element tuple
# instead of requiring the user make a nested tuple
if cls.explicit is not None and isinstance(cls.explicit[0], int_types):
if cls.explicit is not None and isinstance(cls.explicit[0], int):
cls.explicit = (cls.explicit, )
if hasattr(cls, '_setup'):
self._setup()
@ -299,7 +289,7 @@ class Asn1Value(object):
# Normalize tagging values
if explicit is not None:
if isinstance(explicit, int_types):
if isinstance(explicit, int):
if class_ is None:
class_ = 'context'
explicit = (class_, explicit)
@ -309,7 +299,7 @@ class Asn1Value(object):
tag = None
if implicit is not None:
if isinstance(implicit, int_types):
if isinstance(implicit, int):
if class_ is None:
class_ = 'context'
implicit = (class_, implicit)
@ -336,11 +326,11 @@ class Asn1Value(object):
if explicit is not None:
# Ensure we have a tuple of 2-element tuples
if len(explicit) == 2 and isinstance(explicit[1], int_types):
if len(explicit) == 2 and isinstance(explicit[1], int):
explicit = (explicit, )
for class_, tag in explicit:
invalid_class = None
if isinstance(class_, int_types):
if isinstance(class_, int):
if class_ not in CLASS_NUM_TO_NAME_MAP:
invalid_class = class_
else:
@ -356,7 +346,7 @@ class Asn1Value(object):
repr(invalid_class)
))
if tag is not None:
if not isinstance(tag, int_types):
if not isinstance(tag, int):
raise TypeError(unwrap(
'''
explicit tag must be an integer, not %s
@ -379,7 +369,7 @@ class Asn1Value(object):
repr(class_)
))
if tag is not None:
if not isinstance(tag, int_types):
if not isinstance(tag, int):
raise TypeError(unwrap(
'''
implicit tag must be an integer, not %s
@ -445,9 +435,6 @@ class Asn1Value(object):
A unicode string
"""
if _PY2:
return self.__bytes__()
else:
return self.__unicode__()
def __repr__(self):
@ -456,9 +443,6 @@ class Asn1Value(object):
A unicode string
"""
if _PY2:
return '<%s %s b%s>' % (type_name(self), id(self), repr(self.dump()))
else:
return '<%s %s %s>' % (type_name(self), id(self), repr(self.dump()))
def __bytes__(self):
@ -608,9 +592,6 @@ class Asn1Value(object):
self.parsed.debug(nest_level + 2)
elif hasattr(self, 'chosen'):
self.chosen.debug(nest_level + 2)
else:
if _PY2 and isinstance(self.native, byte_cls):
print('%s Native: b%s' % (prefix, repr(self.native)))
else:
print('%s Native: %s' % (prefix, self.native))
@ -1058,7 +1039,7 @@ class Choice(Asn1Value):
A instance of the current class
"""
if not isinstance(encoded_data, byte_cls):
if not isinstance(encoded_data, bytes):
raise TypeError('encoded_data must be a byte string, not %s' % type_name(encoded_data))
value, _ = _parse_build(encoded_data, spec=cls, spec_params=kwargs, strict=strict)
@ -1425,16 +1406,10 @@ class Concat(object):
def __str__(self):
"""
Since str is different in Python 2 and 3, this calls the appropriate
method, __unicode__() or __bytes__()
:return:
A unicode string
"""
if _PY2:
return self.__bytes__()
else:
return self.__unicode__()
def __bytes__(self):
@ -1684,7 +1659,7 @@ class Primitive(Asn1Value):
A byte string
"""
if not isinstance(value, byte_cls):
if not isinstance(value, bytes):
raise TypeError(unwrap(
'''
%s value must be a byte string, not %s
@ -1784,7 +1759,7 @@ class AbstractString(Constructable, Primitive):
A unicode string
"""
if not isinstance(value, str_cls):
if not isinstance(value, str):
raise TypeError(unwrap(
'''
%s value must be a unicode string, not %s
@ -1915,7 +1890,7 @@ class Integer(Primitive, ValueMap):
ValueError - when an invalid value is passed
"""
if isinstance(value, str_cls):
if isinstance(value, str):
if self._map is None:
raise ValueError(unwrap(
'''
@ -1935,7 +1910,7 @@ class Integer(Primitive, ValueMap):
value = self._reverse_map[value]
elif not isinstance(value, int_types):
elif not isinstance(value, int):
raise TypeError(unwrap(
'''
%s value must be an integer or unicode string when a name_map
@ -2004,7 +1979,7 @@ class _IntegerBitString(object):
# return an empty chunk, for cases like \x23\x80\x00\x00
return []
unused_bits_len = ord(self.contents[0]) if _PY2 else self.contents[0]
unused_bits_len = self.contents[0]
value = int_from_bytes(self.contents[1:])
bits = (len(self.contents) - 1) * 8
@ -2135,7 +2110,7 @@ class BitString(_IntegerBitString, Constructable, Castable, Primitive, ValueMap)
if key in value:
bits[index] = 1
value = ''.join(map(str_cls, bits))
value = ''.join(map(str, bits))
elif value.__class__ == tuple:
if self._map is None:
@ -2146,7 +2121,7 @@ class BitString(_IntegerBitString, Constructable, Castable, Primitive, ValueMap)
if bit:
name = self._map.get(index, index)
self._native.add(name)
value = ''.join(map(str_cls, value))
value = ''.join(map(str, value))
else:
raise TypeError(unwrap(
@ -2220,7 +2195,7 @@ class BitString(_IntegerBitString, Constructable, Castable, Primitive, ValueMap)
A boolean if the bit is set
"""
is_int = isinstance(key, int_types)
is_int = isinstance(key, int)
if not is_int:
if not isinstance(self._map, dict):
raise ValueError(unwrap(
@ -2266,7 +2241,7 @@ class BitString(_IntegerBitString, Constructable, Castable, Primitive, ValueMap)
ValueError - when _map is not set or the key name is invalid
"""
is_int = isinstance(key, int_types)
is_int = isinstance(key, int)
if not is_int:
if self._map is None:
raise ValueError(unwrap(
@ -2365,7 +2340,7 @@ class OctetBitString(Constructable, Castable, Primitive):
ValueError - when an invalid value is passed
"""
if not isinstance(value, byte_cls):
if not isinstance(value, bytes):
raise TypeError(unwrap(
'''
%s value must be a byte string, not %s
@ -2435,7 +2410,7 @@ class OctetBitString(Constructable, Castable, Primitive):
List with one tuple, consisting of a byte string and an integer (unused bits)
"""
unused_bits_len = ord(self.contents[0]) if _PY2 else self.contents[0]
unused_bits_len = self.contents[0]
if not unused_bits_len:
return [(self.contents[1:], ())]
@ -2448,11 +2423,11 @@ class OctetBitString(Constructable, Castable, Primitive):
raise ValueError('Bit string has {0} unused bits'.format(unused_bits_len))
mask = (1 << unused_bits_len) - 1
last_byte = ord(self.contents[-1]) if _PY2 else self.contents[-1]
last_byte = self.contents[-1]
# zero out the unused bits in the last byte.
zeroed_byte = last_byte & ~mask
value = self.contents[1:-1] + (chr(zeroed_byte) if _PY2 else bytes((zeroed_byte,)))
value = self.contents[1:-1] + bytes((zeroed_byte,))
unused_bits = _int_to_bit_tuple(last_byte & mask, unused_bits_len)
@ -2505,7 +2480,7 @@ class IntegerBitString(_IntegerBitString, Constructable, Castable, Primitive):
ValueError - when an invalid value is passed
"""
if not isinstance(value, int_types):
if not isinstance(value, int):
raise TypeError(unwrap(
'''
%s value must be a positive integer, not %s
@ -2570,7 +2545,7 @@ class OctetString(Constructable, Castable, Primitive):
A byte string
"""
if not isinstance(value, byte_cls):
if not isinstance(value, bytes):
raise TypeError(unwrap(
'''
%s value must be a byte string, not %s
@ -2654,7 +2629,7 @@ class IntegerOctetString(Constructable, Castable, Primitive):
ValueError - when an invalid value is passed
"""
if not isinstance(value, int_types):
if not isinstance(value, int):
raise TypeError(unwrap(
'''
%s value must be a positive integer, not %s
@ -2752,7 +2727,7 @@ class ParsableOctetString(Constructable, Castable, Primitive):
A byte string
"""
if not isinstance(value, byte_cls):
if not isinstance(value, bytes):
raise TypeError(unwrap(
'''
%s value must be a byte string, not %s
@ -2904,7 +2879,7 @@ class ParsableOctetBitString(ParsableOctetString):
ValueError - when an invalid value is passed
"""
if not isinstance(value, byte_cls):
if not isinstance(value, bytes):
raise TypeError(unwrap(
'''
%s value must be a byte string, not %s
@ -2934,7 +2909,7 @@ class ParsableOctetBitString(ParsableOctetString):
A byte string
"""
unused_bits_len = ord(self.contents[0]) if _PY2 else self.contents[0]
unused_bits_len = self.contents[0]
if unused_bits_len:
raise ValueError('ParsableOctetBitString should have no unused bits')
@ -3007,7 +2982,7 @@ class ObjectIdentifier(Primitive, ValueMap):
type_name(cls)
))
if not isinstance(value, str_cls):
if not isinstance(value, str):
raise TypeError(unwrap(
'''
value must be a unicode string, not %s
@ -3045,7 +3020,7 @@ class ObjectIdentifier(Primitive, ValueMap):
type_name(cls)
))
if not isinstance(value, str_cls):
if not isinstance(value, str):
raise TypeError(unwrap(
'''
value must be a unicode string, not %s
@ -3079,7 +3054,7 @@ class ObjectIdentifier(Primitive, ValueMap):
ValueError - when an invalid value is passed
"""
if not isinstance(value, str_cls):
if not isinstance(value, str):
raise TypeError(unwrap(
'''
%s value must be a unicode string, not %s
@ -3153,24 +3128,22 @@ class ObjectIdentifier(Primitive, ValueMap):
part = 0
for byte in self.contents:
if _PY2:
byte = ord(byte)
part = part * 128
part += byte & 127
# Last byte in subidentifier has the eighth bit set to 0
if byte & 0x80 == 0:
if len(output) == 0:
if part >= 80:
output.append(str_cls(2))
output.append(str_cls(part - 80))
output.append(str(2))
output.append(str(part - 80))
elif part >= 40:
output.append(str_cls(1))
output.append(str_cls(part - 40))
output.append(str(1))
output.append(str(part - 40))
else:
output.append(str_cls(0))
output.append(str_cls(part))
output.append(str(0))
output.append(str(part))
else:
output.append(str_cls(part))
output.append(str(part))
part = 0
self._dotted = '.'.join(output)
@ -3240,7 +3213,7 @@ class Enumerated(Integer):
ValueError - when an invalid value is passed
"""
if not isinstance(value, int_types) and not isinstance(value, str_cls):
if not isinstance(value, int) and not isinstance(value, str):
raise TypeError(unwrap(
'''
%s value must be an integer or a unicode string, not %s
@ -3249,7 +3222,7 @@ class Enumerated(Integer):
type_name(value)
))
if isinstance(value, str_cls):
if isinstance(value, str):
if value not in self._reverse_map:
raise ValueError(unwrap(
'''
@ -3507,7 +3480,7 @@ class Sequence(Asn1Value):
if self.children is None:
self._parse_children()
if not isinstance(key, int_types):
if not isinstance(key, int):
if key not in self._field_map:
raise KeyError(unwrap(
'''
@ -3554,7 +3527,7 @@ class Sequence(Asn1Value):
if self.children is None:
self._parse_children()
if not isinstance(key, int_types):
if not isinstance(key, int):
if key not in self._field_map:
raise KeyError(unwrap(
'''
@ -3605,7 +3578,7 @@ class Sequence(Asn1Value):
if self.children is None:
self._parse_children()
if not isinstance(key, int_types):
if not isinstance(key, int):
if key not in self._field_map:
raise KeyError(unwrap(
'''
@ -4003,7 +3976,7 @@ class Sequence(Asn1Value):
encoded using
"""
if not isinstance(field_name, str_cls):
if not isinstance(field_name, str):
raise TypeError(unwrap(
'''
field_name must be a unicode string, not %s
@ -4051,7 +4024,7 @@ class Sequence(Asn1Value):
try:
name = self._fields[index][0]
except (IndexError):
name = str_cls(index)
name = str(index)
self._native[name] = child.native
except (ValueError, TypeError) as e:
self._native = None
@ -4879,7 +4852,7 @@ class AbstractTime(AbstractString):
A dict with the parsed values
"""
string = str_cls(self)
string = str(self)
m = self._TIMESTRING_RE.match(string)
if not m:
@ -5018,8 +4991,6 @@ class UTCTime(AbstractTime):
raise ValueError('Year of the UTCTime is not in range [1950, 2049], use GeneralizedTime instead')
value = value.strftime('%y%m%d%H%M%SZ')
if _PY2:
value = value.decode('ascii')
AbstractString.set(self, value)
# Set it to None and let the class take care of converting the next
@ -5117,8 +5088,6 @@ class GeneralizedTime(AbstractTime):
fraction = ''
value = value.strftime('%Y%m%d%H%M%S') + fraction + 'Z'
if _PY2:
value = value.decode('ascii')
AbstractString.set(self, value)
# Set it to None and let the class take care of converting the next
@ -5340,7 +5309,7 @@ def _build_id_tuple(params, spec):
else:
required_class = 2
required_tag = params['implicit']
if required_class is not None and not isinstance(required_class, int_types):
if required_class is not None and not isinstance(required_class, int):
required_class = CLASS_NAME_TO_NUM_MAP[required_class]
required_class = params.get('class_', required_class)

View File

@ -20,7 +20,7 @@ import hashlib
import math
from ._errors import unwrap, APIException
from ._types import type_name, byte_cls
from ._types import type_name
from .algos import _ForceNullParameters, DigestAlgorithm, EncryptionAlgorithm, RSAESOAEPParams, RSASSAPSSParams
from .core import (
Any,
@ -582,7 +582,7 @@ class ECPrivateKey(Sequence):
if self._key_size is None:
# Infer the key_size from the existing private key if possible
pkey_contents = self['private_key'].contents
if isinstance(pkey_contents, byte_cls) and len(pkey_contents) > 1:
if isinstance(pkey_contents, bytes) and len(pkey_contents) > 1:
self.set_key_size(len(self['private_key'].contents))
elif self._key_size is not None:
@ -744,7 +744,7 @@ class PrivateKeyInfo(Sequence):
A PrivateKeyInfo object
"""
if not isinstance(private_key, byte_cls) and not isinstance(private_key, Asn1Value):
if not isinstance(private_key, bytes) and not isinstance(private_key, Asn1Value):
raise TypeError(unwrap(
'''
private_key must be a byte string or Asn1Value, not %s
@ -1112,7 +1112,7 @@ class PublicKeyInfo(Sequence):
A PublicKeyInfo object
"""
if not isinstance(public_key, byte_cls) and not isinstance(public_key, Asn1Value):
if not isinstance(public_key, bytes) and not isinstance(public_key, Asn1Value):
raise TypeError(unwrap(
'''
public_key must be a byte string or Asn1Value, not %s
@ -1268,7 +1268,7 @@ class PublicKeyInfo(Sequence):
"""
if self._sha1 is None:
self._sha1 = hashlib.sha1(byte_cls(self['public_key'])).digest()
self._sha1 = hashlib.sha1(bytes(self['public_key'])).digest()
return self._sha1
@property
@ -1279,7 +1279,7 @@ class PublicKeyInfo(Sequence):
"""
if self._sha256 is None:
self._sha256 = hashlib.sha256(byte_cls(self['public_key'])).digest()
self._sha256 = hashlib.sha256(bytes(self['public_key'])).digest()
return self._sha256
@property

View File

@ -15,10 +15,9 @@ from __future__ import unicode_literals, division, absolute_import, print_functi
import sys
from ._types import byte_cls, chr_cls, type_name
from ._types import chr_cls, type_name
from .util import int_from_bytes, int_to_bytes
_PY2 = sys.version_info <= (3,)
_INSUFFICIENT_DATA_MESSAGE = 'Insufficient data - %s bytes requested but only %s available'
_MAX_DEPTH = 10
@ -66,7 +65,7 @@ def emit(class_, method, tag, contents):
if tag < 0:
raise ValueError('tag must be greater than zero, not %s' % tag)
if not isinstance(contents, byte_cls):
if not isinstance(contents, bytes):
raise TypeError('contents must be a byte string, not %s' % type_name(contents))
return _dump_header(class_, method, tag, contents) + contents
@ -101,7 +100,7 @@ def parse(contents, strict=False):
- 5: byte string trailer
"""
if not isinstance(contents, byte_cls):
if not isinstance(contents, bytes):
raise TypeError('contents must be a byte string, not %s' % type_name(contents))
contents_len = len(contents)
@ -130,7 +129,7 @@ def peek(contents):
An integer with the number of bytes occupied by the ASN.1 value
"""
if not isinstance(contents, byte_cls):
if not isinstance(contents, bytes):
raise TypeError('contents must be a byte string, not %s' % type_name(contents))
info, consumed = _parse(contents, len(contents))
@ -171,7 +170,7 @@ def _parse(encoded_data, data_len, pointer=0, lengths_only=False, depth=0):
if data_len < pointer + 1:
raise ValueError(_INSUFFICIENT_DATA_MESSAGE % (1, data_len - pointer))
first_octet = ord(encoded_data[pointer]) if _PY2 else encoded_data[pointer]
first_octet = encoded_data[pointer]
pointer += 1
@ -183,7 +182,7 @@ def _parse(encoded_data, data_len, pointer=0, lengths_only=False, depth=0):
while True:
if data_len < pointer + 1:
raise ValueError(_INSUFFICIENT_DATA_MESSAGE % (1, data_len - pointer))
num = ord(encoded_data[pointer]) if _PY2 else encoded_data[pointer]
num = encoded_data[pointer]
pointer += 1
if num == 0x80 and tag == 0:
raise ValueError('Non-minimal tag encoding')
@ -196,7 +195,7 @@ def _parse(encoded_data, data_len, pointer=0, lengths_only=False, depth=0):
if data_len < pointer + 1:
raise ValueError(_INSUFFICIENT_DATA_MESSAGE % (1, data_len - pointer))
length_octet = ord(encoded_data[pointer]) if _PY2 else encoded_data[pointer]
length_octet = encoded_data[pointer]
pointer += 1
trailer = b''

View File

@ -11,17 +11,13 @@ Encoding DER to PEM and decoding PEM to DER. Exports the following items:
from __future__ import unicode_literals, division, absolute_import, print_function
from io import BytesIO
import base64
import re
import sys
from ._errors import unwrap
from ._types import type_name as _type_name, str_cls, byte_cls
from ._types import type_name as _type_name
if sys.version_info < (3,):
from cStringIO import StringIO as BytesIO
else:
from io import BytesIO
def detect(byte_string):
@ -36,7 +32,7 @@ def detect(byte_string):
string
"""
if not isinstance(byte_string, byte_cls):
if not isinstance(byte_string, bytes):
raise TypeError(unwrap(
'''
byte_string must be a byte string, not %s
@ -67,14 +63,14 @@ def armor(type_name, der_bytes, headers=None):
A byte string of the PEM block
"""
if not isinstance(der_bytes, byte_cls):
if not isinstance(der_bytes, bytes):
raise TypeError(unwrap(
'''
der_bytes must be a byte string, not %s
''' % _type_name(der_bytes)
))
if not isinstance(type_name, str_cls):
if not isinstance(type_name, str):
raise TypeError(unwrap(
'''
type_name must be a unicode string, not %s
@ -127,7 +123,7 @@ def _unarmor(pem_bytes):
in the form "Name: Value" that are right after the begin line.
"""
if not isinstance(pem_bytes, byte_cls):
if not isinstance(pem_bytes, bytes):
raise TypeError(unwrap(
'''
pem_bytes must be a byte string, not %s

View File

@ -20,11 +20,11 @@ from __future__ import unicode_literals, division, absolute_import, print_functi
import math
import sys
from datetime import datetime, date, timedelta, tzinfo
from collections import OrderedDict
from datetime import datetime, date, timedelta, timezone, tzinfo
from ._errors import unwrap
from ._iri import iri_to_uri, uri_to_iri # noqa
from ._ordereddict import OrderedDict # noqa
from ._types import type_name
if sys.platform == 'win32':
@ -33,185 +33,8 @@ else:
from socket import inet_ntop, inet_pton # noqa
# Python 2
if sys.version_info <= (3,):
def int_to_bytes(value, signed=False, width=None):
"""
Converts an integer to a byte string
:param value:
The integer to convert
:param signed:
If the byte string should be encoded using two's complement
:param width:
If None, the minimal possible size (but at least 1),
otherwise an integer of the byte width for the return value
:return:
A byte string
"""
if value == 0 and width == 0:
return b''
# Handle negatives in two's complement
is_neg = False
if signed and value < 0:
is_neg = True
bits = int(math.ceil(len('%x' % abs(value)) / 2.0) * 8)
value = (value + (1 << bits)) % (1 << bits)
hex_str = '%x' % value
if len(hex_str) & 1:
hex_str = '0' + hex_str
output = hex_str.decode('hex')
if signed and not is_neg and ord(output[0:1]) & 0x80:
output = b'\x00' + output
if width is not None:
if len(output) > width:
raise OverflowError('int too big to convert')
if is_neg:
pad_char = b'\xFF'
else:
pad_char = b'\x00'
output = (pad_char * (width - len(output))) + output
elif is_neg and ord(output[0:1]) & 0x80 == 0:
output = b'\xFF' + output
return output
def int_from_bytes(value, signed=False):
"""
Converts a byte string to an integer
:param value:
The byte string to convert
:param signed:
If the byte string should be interpreted using two's complement
:return:
An integer
"""
if value == b'':
return 0
num = long(value.encode("hex"), 16) # noqa
if not signed:
return num
# Check for sign bit and handle two's complement
if ord(value[0:1]) & 0x80:
bit_len = len(value) * 8
return num - (1 << bit_len)
return num
class timezone(tzinfo): # noqa
"""
Implements datetime.timezone for py2.
Only full minute offsets are supported.
DST is not supported.
"""
def __init__(self, offset, name=None):
"""
:param offset:
A timedelta with this timezone's offset from UTC
:param name:
Name of the timezone; if None, generate one.
"""
if not timedelta(hours=-24) < offset < timedelta(hours=24):
raise ValueError('Offset must be in [-23:59, 23:59]')
if offset.seconds % 60 or offset.microseconds:
raise ValueError('Offset must be full minutes')
self._offset = offset
if name is not None:
self._name = name
elif not offset:
self._name = 'UTC'
else:
self._name = 'UTC' + _format_offset(offset)
def __eq__(self, other):
"""
Compare two timezones
:param other:
The other timezone to compare to
:return:
A boolean
"""
if type(other) != timezone:
return False
return self._offset == other._offset
def __getinitargs__(self):
"""
Called by tzinfo.__reduce__ to support pickle and copy.
:return:
offset and name, to be used for __init__
"""
return self._offset, self._name
def tzname(self, dt):
"""
:param dt:
A datetime object; ignored.
:return:
Name of this timezone
"""
return self._name
def utcoffset(self, dt):
"""
:param dt:
A datetime object; ignored.
:return:
A timedelta object with the offset from UTC
"""
return self._offset
def dst(self, dt):
"""
:param dt:
A datetime object; ignored.
:return:
Zero timedelta
"""
return timedelta(0)
timezone.utc = timezone(timedelta(0))
# Python 3
else:
from datetime import timezone # noqa
def int_to_bytes(value, signed=False, width=None):
def int_to_bytes(value, signed=False, width=None):
"""
Converts an integer to a byte string
@ -242,7 +65,7 @@ else:
width = math.ceil(bits_required / 8) or 1
return value.to_bytes(width, byteorder='big', signed=signed)
def int_from_bytes(value, signed=False):
def int_from_bytes(value, signed=False):
"""
Converts a byte string to an integer

View File

@ -15,6 +15,7 @@ Other type classes are defined that help compose the types listed above.
from __future__ import unicode_literals, division, absolute_import, print_function
from collections import OrderedDict
from contextlib import contextmanager
from encodings import idna # noqa
import hashlib
@ -26,8 +27,7 @@ import unicodedata
from ._errors import unwrap
from ._iri import iri_to_uri, uri_to_iri
from ._ordereddict import OrderedDict
from ._types import type_name, str_cls, bytes_to_list
from ._types import type_name
from .algos import AlgorithmIdentifier, AnyAlgorithmIdentifier, DigestAlgorithm, SignedDigestAlgorithm
from .core import (
Any,
@ -100,7 +100,7 @@ class DNSName(IA5String):
A unicode string
"""
if not isinstance(value, str_cls):
if not isinstance(value, str):
raise TypeError(unwrap(
'''
%s value must be a unicode string, not %s
@ -131,7 +131,7 @@ class URI(IA5String):
A unicode string
"""
if not isinstance(value, str_cls):
if not isinstance(value, str):
raise TypeError(unwrap(
'''
%s value must be a unicode string, not %s
@ -215,7 +215,7 @@ class EmailAddress(IA5String):
A unicode string
"""
if not isinstance(value, str_cls):
if not isinstance(value, str):
raise TypeError(unwrap(
'''
%s value must be a unicode string, not %s
@ -323,7 +323,7 @@ class IPAddress(OctetString):
an IPv6 address or IPv6 address with CIDR
"""
if not isinstance(value, str_cls):
if not isinstance(value, str):
raise TypeError(unwrap(
'''
%s value must be a unicode string, not %s
@ -413,7 +413,7 @@ class IPAddress(OctetString):
if cidr_int is not None:
cidr_bits = '{0:b}'.format(cidr_int)
cidr = len(cidr_bits.rstrip('0'))
value = value + '/' + str_cls(cidr)
value = value + '/' + str(cidr)
self._native = value
return self._native
@ -2598,7 +2598,7 @@ class Certificate(Sequence):
"""
if self._issuer_serial is None:
self._issuer_serial = self.issuer.sha256 + b':' + str_cls(self.serial_number).encode('ascii')
self._issuer_serial = self.issuer.sha256 + b':' + str(self.serial_number).encode('ascii')
return self._issuer_serial
@property
@ -2647,7 +2647,7 @@ class Certificate(Sequence):
# We untag the element since it is tagged via being a choice from GeneralName
issuer = issuer.untag()
authority_serial = self.authority_key_identifier_value['authority_cert_serial_number'].native
self._authority_issuer_serial = issuer.sha256 + b':' + str_cls(authority_serial).encode('ascii')
self._authority_issuer_serial = issuer.sha256 + b':' + str(authority_serial).encode('ascii')
else:
self._authority_issuer_serial = None
return self._authority_issuer_serial
@ -2860,7 +2860,7 @@ class Certificate(Sequence):
with a space between each pair of characters, all uppercase
"""
return ' '.join('%02X' % c for c in bytes_to_list(self.sha1))
return ' '.join('%02X' % c for c in list(self.sha1))
@property
def sha256(self):
@ -2882,7 +2882,7 @@ class Certificate(Sequence):
with a space between each pair of characters, all uppercase
"""
return ' '.join('%02X' % c for c in bytes_to_list(self.sha256))
return ' '.join('%02X' % c for c in list(self.sha256))
def is_valid_domain_ip(self, domain_ip):
"""
@ -2896,7 +2896,7 @@ class Certificate(Sequence):
A boolean - if the domain or IP is valid for the certificate
"""
if not isinstance(domain_ip, str_cls):
if not isinstance(domain_ip, str):
raise TypeError(unwrap(
'''
domain_ip must be a unicode string, not %s

View File

@ -28,13 +28,13 @@
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
# OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import string
if sys.version_info >= (3, 0):
def unichr(character): # pylint: disable=redefined-builtin
def unichr(character): # pylint: disable=redefined-builtin
return chr(character)
def ConvertNEXTSTEPToUnicode(hex_digits):
# taken from http://ftp.unicode.org/Public/MAPPINGS/VENDORS/NEXT/NEXTSTEP.TXT
conversion = {

View File

@ -64,12 +64,10 @@ def GetFileEncoding(path):
def OpenFileWithEncoding(file_path, encoding):
return codecs.open(file_path, 'r', encoding=encoding, errors='ignore')
if sys.version_info < (3, 0):
def OpenFile(file_path):
def OpenFile(file_path):
return open(file_path, 'rb')
else:
def OpenFile(file_path):
return open(file_path, 'br')
class PBParser(object):

View File

@ -32,7 +32,7 @@ import sys
from functools import cmp_to_key
# for python 3.10+ compatibility
if sys.version_info.major == 3 and sys.version_info.minor >= 10:
if sys.version_info >= (3, 10):
import collections
setattr(collections, "MutableMapping", collections.abc.MutableMapping)