Skip to content

Fix to remove python 2 & python 3 switches using if statements #1168

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

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
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
5 changes: 1 addition & 4 deletions appveyor.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
environment:
matrix:
- PYTHON: "C:\\Python27-x64"
cassandra_version: 3.11.2
ci_type: standard
- PYTHON: "C:\\Python35-x64"
- PYTHON: "C:\\Python37-x64"
cassandra_version: 3.11.2
ci_type: standard
os: Visual Studio 2015
Expand Down
2 changes: 1 addition & 1 deletion cassandra/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ def get_initial_challenge(self):
def evaluate_challenge(self, challenge):
if challenge == six.b('PLAIN-START'):
data = "\x00%s\x00%s" % (self.username, self.password)
return data if six.PY2 else data.encode()
return data.encode()
raise Exception('Did not receive a valid challenge response from server')


Expand Down
6 changes: 0 additions & 6 deletions cassandra/cluster.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,6 @@
except ImportError:
from cassandra.util import WeakSet # NOQA

if six.PY3:
long = int

def _is_eventlet_monkey_patched():
if 'eventlet.patcher' not in sys.modules:
Expand Down Expand Up @@ -3345,10 +3343,6 @@ def user_type_registered(self, keyspace, user_type, klass):
'User type %s does not exist in keyspace %s' % (user_type, keyspace))

field_names = type_meta.field_names
if six.PY2:
# go from unicode to string to avoid decode errors from implicit
# decode when formatting non-ascii values
field_names = [fn.encode('utf-8') for fn in field_names]

def encode(val):
return '{ %s }' % ' , '.join('%s : %s' % (
Expand Down
7 changes: 1 addition & 6 deletions cassandra/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import six

if six.PY2:
from collections import Mapping
elif six.PY3:
from collections.abc import Mapping
from collections.abc import Mapping
11 changes: 3 additions & 8 deletions cassandra/concurrent.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,15 +145,14 @@ def _execute(self, idx, statement, params):
except Exception as exc:
# exc_info with fail_fast to preserve stack trace info when raising on the client thread
# (matches previous behavior -- not sure why we wouldn't want stack trace in the other case)
e = sys.exc_info() if self._fail_fast and six.PY2 else exc

# If we're not failing fast and all executions are raising, there is a chance of recursing
# here as subsequent requests are attempted. If we hit this threshold, schedule this result/retry
# and let the event loop thread return.
if self._exec_depth < self.max_error_recursion:
self._put_result(e, idx, False)
self._put_result(exc, idx, False)
else:
self.session.submit(self._put_result, e, idx, False)
self.session.submit(self._put_result, exc, idx, False)
self._exec_depth -= 1

def _on_success(self, result, future, idx):
Expand All @@ -165,11 +164,7 @@ def _on_error(self, result, future, idx):

@staticmethod
def _raise(exc):
if six.PY2 and isinstance(exc, tuple):
(exc_type, value, traceback) = exc
six.reraise(exc_type, value, traceback)
else:
raise exc
raise exc


class ConcurrentExecutorGenResults(_ConcurrentExecutor):
Expand Down
7 changes: 2 additions & 5 deletions cassandra/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -605,11 +605,8 @@ def wrapper(self, *args, **kwargs):

DEFAULT_CQL_VERSION = '3.0.0'

if six.PY3:
def int_from_buf_item(i):
return i
else:
int_from_buf_item = ord
def int_from_buf_item(i):
return i


class _ConnectionIOBuffer(object):
Expand Down
8 changes: 2 additions & 6 deletions cassandra/cqlengine/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import six


# Caching constants.
CACHING_ALL = "ALL"
Expand All @@ -31,7 +29,5 @@ class ValidationError(CQLEngineException):


class UnicodeMixin(object):
if six.PY3:
__str__ = lambda x: x.__unicode__()
else:
__str__ = lambda x: six.text_type(x).encode('utf-8')
__str__ = lambda x: x.__unicode__()

74 changes: 26 additions & 48 deletions cassandra/cqltypes.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Copyright DataStax, Inc.
# Copyright DataStax, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -54,10 +54,9 @@
from cassandra import util

_little_endian_flag = 1 # we always serialize LE
if six.PY3:
import ipaddress
import ipaddress

_ord = ord if six.PY2 else lambda x: x
_ord = lambda x: x

apache_cassandra_type_prefix = 'org.apache.cassandra.db.marshal.'

Expand All @@ -66,16 +65,11 @@

log = logging.getLogger(__name__)

if six.PY3:
_number_types = frozenset((int, float))
long = int
_number_types = frozenset((int, float))

def _name_from_hex_string(encoded_name):
bin_str = unhexlify(encoded_name)
return bin_str.decode('ascii')
else:
_number_types = frozenset((int, long, float))
_name_from_hex_string = unhexlify
def _name_from_hex_string(encoded_name):
bin_str = unhexlify(encoded_name)
return bin_str.decode('ascii')


def trim_if_startswith(s, prefix):
Expand Down Expand Up @@ -383,8 +377,6 @@ def apply_parameters(cls, subtypes, names=None):
raise ValueError("%s types require %d subtypes (%d given)"
% (cls.typename, cls.num_subtypes, len(subtypes)))
newname = cls.cass_parameterized_type_with(subtypes)
if six.PY2 and isinstance(newname, unicode):
newname = newname.encode('utf-8')
return type(newname, (cls,), {'subtypes': subtypes, 'cassname': cls.cassname, 'fieldnames': names})

@classmethod
Expand Down Expand Up @@ -415,16 +407,10 @@ class _UnrecognizedType(_CassandraType):
num_subtypes = 'UNKNOWN'


if six.PY3:
def mkUnrecognizedType(casstypename):
return CassandraTypeType(casstypename,
(_UnrecognizedType,),
{'typename': "'%s'" % casstypename})
else:
def mkUnrecognizedType(casstypename): # noqa
return CassandraTypeType(casstypename.encode('utf8'),
(_UnrecognizedType,),
{'typename': "'%s'" % casstypename})
def mkUnrecognizedType(casstypename):
return CassandraTypeType(casstypename,
(_UnrecognizedType,),
{'typename': "'%s'" % casstypename})


class BytesType(_CassandraType):
Expand Down Expand Up @@ -500,25 +486,21 @@ def serialize(byts, protocol_version):
return int8_pack(byts)


if six.PY2:
class AsciiType(_CassandraType):
typename = 'ascii'
empty_binary_ok = True
else:
class AsciiType(_CassandraType):
typename = 'ascii'
empty_binary_ok = True

@staticmethod
def deserialize(byts, protocol_version):
return byts.decode('ascii')
class AsciiType(_CassandraType):
typename = 'ascii'
empty_binary_ok = True

@staticmethod
def serialize(var, protocol_version):
try:
return var.encode('ascii')
except UnicodeDecodeError:
return var
@staticmethod
def deserialize(byts, protocol_version):
return byts.decode('ascii')

@staticmethod
def serialize(var, protocol_version):
try:
return var.encode('ascii')
except UnicodeDecodeError:
return var


class FloatType(_CassandraType):
Expand Down Expand Up @@ -603,7 +585,7 @@ def serialize(addr, protocol_version):
# since we've already determined the AF
return socket.inet_aton(addr)
except:
if six.PY3 and isinstance(addr, (ipaddress.IPv4Address, ipaddress.IPv6Address)):
if isinstance(addr, (ipaddress.IPv4Address, ipaddress.IPv6Address)):
return addr.packed
raise ValueError("can't interpret %r as an inet address" % (addr,))

Expand Down Expand Up @@ -662,7 +644,7 @@ def serialize(v, protocol_version):
raise TypeError('DateType arguments must be a datetime, date, or timestamp')
timestamp = v

return int64_pack(long(timestamp))
return int64_pack(int(timestamp))


class TimestampType(DateType):
Expand Down Expand Up @@ -975,8 +957,6 @@ class UserType(TupleType):
def make_udt_class(cls, keyspace, udt_name, field_names, field_types):
assert len(field_names) == len(field_types)

if six.PY2 and isinstance(udt_name, unicode):
udt_name = udt_name.encode('utf-8')

instance = cls._cache.get((keyspace, udt_name))
if not instance or instance.fieldnames != field_names or instance.subtypes != field_types:
Expand All @@ -992,8 +972,6 @@ def make_udt_class(cls, keyspace, udt_name, field_names, field_types):

@classmethod
def evict_udt_class(cls, keyspace, udt_name):
if six.PY2 and isinstance(udt_name, unicode):
udt_name = udt_name.encode('utf-8')
try:
del cls._cache[(keyspace, udt_name)]
except KeyError:
Expand Down
21 changes: 5 additions & 16 deletions cassandra/datastax/graph/graphson.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,9 +164,7 @@ class Int64TypeIO(IntegerTypeIO):

@classmethod
def deserialize(cls, value, reader=None):
if six.PY3:
return value
return long(value)
return value


class FloatTypeIO(GraphSONTypeIO):
Expand Down Expand Up @@ -274,8 +272,7 @@ class BlobTypeIO(GraphSONTypeIO):
@classmethod
def serialize(cls, value, writer=None):
value = base64.b64encode(value)
if six.PY3:
value = value.decode('utf-8')
value = value.decode('utf-8')
return value

@classmethod
Expand Down Expand Up @@ -845,12 +842,8 @@ class GraphSON1Serializer(_BaseGraphSONSerializer):
GraphSON1Serializer.register(ipaddress.IPv4Address, InetTypeIO)
GraphSON1Serializer.register(ipaddress.IPv6Address, InetTypeIO)

if six.PY2:
GraphSON1Serializer.register(buffer, ByteBufferTypeIO)
GraphSON1Serializer.register(unicode, TextTypeIO)
else:
GraphSON1Serializer.register(memoryview, ByteBufferTypeIO)
GraphSON1Serializer.register(bytes, ByteBufferTypeIO)
GraphSON1Serializer.register(memoryview, ByteBufferTypeIO)
GraphSON1Serializer.register(bytes, ByteBufferTypeIO)


class _BaseGraphSONDeserializer(object):
Expand Down Expand Up @@ -922,9 +915,7 @@ def deserialize_int(cls, value):

@classmethod
def deserialize_bigint(cls, value):
if six.PY3:
return cls.deserialize_int(value)
return long(value)
return cls.deserialize_int(value)

@classmethod
def deserialize_double(cls, value):
Expand Down Expand Up @@ -1007,8 +998,6 @@ def serialize(self, value, writer=None):


GraphSON2Serializer.register(int, IntegerTypeIO)
if six.PY2:
GraphSON2Serializer.register(long, IntegerTypeIO)


class GraphSON2Deserializer(_BaseGraphSONDeserializer):
Expand Down
6 changes: 3 additions & 3 deletions cassandra/datastax/insights/reporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,9 +199,9 @@ def _get_startup_data(self):
},
'platformInfo': {
'os': {
'name': uname_info.system if six.PY3 else uname_info[0],
'version': uname_info.release if six.PY3 else uname_info[2],
'arch': uname_info.machine if six.PY3 else uname_info[4]
'name': uname_info.system,
'version': uname_info.release,
'arch': uname_info.machine
},
'cpus': {
'length': multiprocessing.cpu_count(),
Expand Down
Loading