Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 2ff1672

Browse files
bschoeningabsurdfarce
authored andcommitted
CASSPYTHON-18: removed obsolete check for python version > 3.7+
patch by Brad Schoening; reviewed by Brad Schoening and Bret McGuire
1 parent e80ef69 commit 2ff1672

12 files changed

Lines changed: 31 additions & 232 deletions

File tree

cassandra/cluster.py

Lines changed: 1 addition & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1389,7 +1389,7 @@ def __init__(self,
13891389
HostDistance.REMOTE: DEFAULT_MAX_CONNECTIONS_PER_REMOTE_HOST
13901390
}
13911391

1392-
self.executor = self._create_thread_pool_executor(max_workers=executor_threads)
1392+
self.executor = ThreadPoolExecutor(max_workers=executor_threads)
13931393
self.scheduler = _Scheduler(self.executor)
13941394

13951395
self._lock = RLock()
@@ -1411,42 +1411,6 @@ def __init__(self,
14111411
if application_version is not None:
14121412
self.application_version = application_version
14131413

1414-
def _create_thread_pool_executor(self, **kwargs):
1415-
"""
1416-
Create a ThreadPoolExecutor for the cluster. In most cases, the built-in
1417-
`concurrent.futures.ThreadPoolExecutor` is used.
1418-
1419-
Python 3.7+ and Eventlet cause the `concurrent.futures.ThreadPoolExecutor`
1420-
to hang indefinitely. In that case, the user needs to have the `futurist`
1421-
package so we can use the `futurist.GreenThreadPoolExecutor` class instead.
1422-
1423-
:param kwargs: All keyword args are passed to the ThreadPoolExecutor constructor.
1424-
:return: A ThreadPoolExecutor instance.
1425-
"""
1426-
tpe_class = ThreadPoolExecutor
1427-
if sys.version_info[0] >= 3 and sys.version_info[1] >= 7:
1428-
try:
1429-
from cassandra.io.eventletreactor import EventletConnection
1430-
is_eventlet = issubclass(self.connection_class, EventletConnection)
1431-
except:
1432-
# Eventlet is not available or can't be detected
1433-
return tpe_class(**kwargs)
1434-
1435-
if is_eventlet:
1436-
try:
1437-
from futurist import GreenThreadPoolExecutor
1438-
tpe_class = GreenThreadPoolExecutor
1439-
except ImportError:
1440-
# futurist is not available
1441-
raise ImportError(
1442-
("Python 3.7+ and Eventlet cause the `concurrent.futures.ThreadPoolExecutor` "
1443-
"to hang indefinitely. If you want to use the Eventlet reactor, you "
1444-
"need to install the `futurist` package to allow the driver to use "
1445-
"the GreenThreadPoolExecutor. See https://github.com/eventlet/eventlet/issues/508 "
1446-
"for more details."))
1447-
1448-
return tpe_class(**kwargs)
1449-
14501414
def register_user_type(self, keyspace, user_type, klass):
14511415
"""
14521416
Registers a class to use to represent a particular user-defined type.

cassandra/query.py

Lines changed: 0 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -85,40 +85,6 @@ def tuple_factory(colnames, rows):
8585
"""
8686
return rows
8787

88-
class PseudoNamedTupleRow(object):
89-
"""
90-
Helper class for pseudo_named_tuple_factory. These objects provide an
91-
__iter__ interface, as well as index- and attribute-based access to values,
92-
but otherwise do not attempt to implement the full namedtuple or iterable
93-
interface.
94-
"""
95-
def __init__(self, ordered_dict):
96-
self._dict = ordered_dict
97-
self._tuple = tuple(ordered_dict.values())
98-
99-
def __getattr__(self, name):
100-
return self._dict[name]
101-
102-
def __getitem__(self, idx):
103-
return self._tuple[idx]
104-
105-
def __iter__(self):
106-
return iter(self._tuple)
107-
108-
def __repr__(self):
109-
return '{t}({od})'.format(t=self.__class__.__name__,
110-
od=self._dict)
111-
112-
113-
def pseudo_namedtuple_factory(colnames, rows):
114-
"""
115-
Returns each row as a :class:`.PseudoNamedTupleRow`. This is the fallback
116-
factory for cases where :meth:`.named_tuple_factory` fails to create rows.
117-
"""
118-
return [PseudoNamedTupleRow(od)
119-
for od in ordered_dict_factory(colnames, rows)]
120-
121-
12288
def named_tuple_factory(colnames, rows):
12389
"""
12490
Returns each row as a `namedtuple <https://docs.python.org/2/library/collections.html#collections.namedtuple>`_.
@@ -151,20 +117,6 @@ def named_tuple_factory(colnames, rows):
151117
clean_column_names = map(_clean_column_name, colnames)
152118
try:
153119
Row = namedtuple('Row', clean_column_names)
154-
except SyntaxError:
155-
warnings.warn(
156-
"Failed creating namedtuple for a result because there were too "
157-
"many columns. This is due to a Python limitation that affects "
158-
"namedtuple in Python 3.0-3.6 (see issue18896). The row will be "
159-
"created with {substitute_factory_name}, which lacks some namedtuple "
160-
"features and is slower. To avoid slower performance accessing "
161-
"values on row objects, Upgrade to Python 3.7, or use a different "
162-
"row factory. (column names: {colnames})".format(
163-
substitute_factory_name=pseudo_namedtuple_factory.__name__,
164-
colnames=colnames
165-
)
166-
)
167-
return pseudo_namedtuple_factory(colnames, rows)
168120
except Exception:
169121
clean_column_names = list(map(_clean_column_name, colnames)) # create list because py3 map object will be consumed by first attempt
170122
log.warning("Failed creating named tuple for results with column names %s (cleaned: %s) "

test-requirements.txt

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,4 @@ gevent
99
eventlet
1010
cython>=3.0
1111
packaging
12-
futurist
1312
asynctest

tests/__init__.py

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -77,13 +77,6 @@ def is_monkey_patched():
7777

7878
from cassandra.io.eventletreactor import EventletConnection
7979
connection_class = EventletConnection
80-
81-
try:
82-
from futurist import GreenThreadPoolExecutor
83-
thread_pool_executor_class = GreenThreadPoolExecutor
84-
except:
85-
# futurist is installed only with python >=3.7
86-
pass
8780
elif "asyncore" in EVENT_LOOP_MANAGER:
8881
from cassandra.io.asyncorereactor import AsyncoreConnection
8982
connection_class = AsyncoreConnection

tests/integration/advanced/graph/fluent/__init__.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -585,10 +585,7 @@ def _validate_prop(key, value, unittest):
585585
typ = int
586586

587587
elif any(key.startswith(t) for t in ('long',)):
588-
if sys.version_info >= (3, 0):
589-
typ = int
590-
else:
591-
typ = long
588+
typ = int
592589
elif any(key.startswith(t) for t in ('float', 'double')):
593590
typ = float
594591
elif any(key.startswith(t) for t in ('polygon',)):

tests/integration/cqlengine/base.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,13 @@
1515
# limitations under the License.
1616
import unittest
1717

18-
import sys
19-
2018
from cassandra.cqlengine.connection import get_session
2119
from cassandra.cqlengine.models import Model
2220
from cassandra.cqlengine import columns
2321

2422
from uuid import uuid4
2523

24+
2625
class TestQueryUpdateModel(Model):
2726

2827
partition = columns.UUID(primary_key=True, default=uuid4)
@@ -33,6 +32,7 @@ class TestQueryUpdateModel(Model):
3332
text_list = columns.List(columns.Text, required=False)
3433
text_map = columns.Map(columns.Text, columns.Text, required=False)
3534

35+
3636
class BaseCassEngTestCase(unittest.TestCase):
3737

3838
session = None
@@ -48,6 +48,5 @@ def assertNotHasAttr(self, obj, attr):
4848
self.assertFalse(hasattr(obj, attr),
4949
"{0} shouldn't have the attribute: {1}".format(obj, attr))
5050

51-
if sys.version_info > (3, 0):
52-
def assertItemsEqual(self, first, second, msg=None):
53-
return self.assertCountEqual(first, second, msg)
51+
def assertItemsEqual(self, first, second, msg=None):
52+
return self.assertCountEqual(first, second, msg)

tests/integration/cqlengine/columns/test_validation.py

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ def test_datetime_tzinfo_io(self):
6161
class TZ(tzinfo):
6262
def utcoffset(self, date_time):
6363
return timedelta(hours=-1)
64+
6465
def dst(self, date_time):
6566
return None
6667

@@ -91,7 +92,7 @@ def test_datetime_none(self):
9192
self.assertIsNone(dts[0][0])
9293

9394
def test_datetime_invalid(self):
94-
dt_value= 'INVALID'
95+
dt_value = 'INVALID'
9596
with self.assertRaises(TypeError):
9697
self.DatetimeTest.objects.create(test_id=4, created_at=dt_value)
9798

@@ -125,7 +126,7 @@ def test_datetime_truncate_microseconds(self):
125126
dt_truncated = datetime(2024, 12, 31, 10, 10, 10, 923000)
126127
self.DatetimeTest.objects.create(test_id=6, created_at=dt_value)
127128
dt2 = self.DatetimeTest.objects(test_id=6).first()
128-
self.assertEqual(dt2.created_at,dt_truncated)
129+
self.assertEqual(dt2.created_at, dt_truncated)
129130
finally:
130131
# We need to always return behavior to default
131132
DateTime.truncate_microseconds = False
@@ -191,7 +192,7 @@ def test_varint_io(self):
191192
self.VarIntTest.objects.create(test_id=0, bignum="not_a_number")
192193

193194

194-
class DataType():
195+
class DataType:
195196
@classmethod
196197
def setUpClass(cls):
197198
if PROTOCOL_VERSION < 4 or CASSANDRA_VERSION < Version("3.0"):
@@ -344,6 +345,7 @@ def setUpClass(cls):
344345
)
345346
super(TestBoolean, cls).setUpClass()
346347

348+
347349
@greaterthanorequalcass3_11
348350
class TestDuration(DataType, BaseCassEngTestCase):
349351
@classmethod
@@ -507,7 +509,7 @@ def test_timeuuid_io(self):
507509
class TestInteger(BaseCassEngTestCase):
508510
class IntegerTest(Model):
509511

510-
test_id = UUID(primary_key=True, default=lambda:uuid4())
512+
test_id = UUID(primary_key=True, default=lambda: uuid4())
511513
value = Integer(default=0, required=True)
512514

513515
def test_default_zero_fields_validate(self):
@@ -519,8 +521,8 @@ def test_default_zero_fields_validate(self):
519521
class TestBigInt(BaseCassEngTestCase):
520522
class BigIntTest(Model):
521523

522-
test_id = UUID(primary_key=True, default=lambda:uuid4())
523-
value = BigInt(default=0, required=True)
524+
test_id = UUID(primary_key=True, default=lambda: uuid4())
525+
value = BigInt(default=0, required=True)
524526

525527
def test_default_zero_fields_validate(self):
526528
""" Tests that bigint columns with a default value of 0 validate """
@@ -612,10 +614,6 @@ def test_type_checking(self):
612614
with self.assertRaises(ValidationError):
613615
Ascii().validate('Beyonc' + chr(233))
614616

615-
if sys.version_info < (3, 1):
616-
with self.assertRaises(ValidationError):
617-
Ascii().validate(u'Beyonc' + unichr(233))
618-
619617
def test_unaltering_validation(self):
620618
""" Test the validation step doesn't re-interpret values. """
621619
self.assertEqual(Ascii().validate(''), '')
@@ -736,8 +734,6 @@ def test_type_checking(self):
736734

737735
Text().validate("!#$%&\'()*+,-./")
738736
Text().validate('Beyonc' + chr(233))
739-
if sys.version_info < (3, 1):
740-
Text().validate(u'Beyonc' + unichr(233))
741737

742738
def test_unaltering_validation(self):
743739
""" Test the validation step doesn't re-interpret values. """
@@ -810,7 +806,7 @@ def test_conversion_specific_date(self):
810806
from uuid import UUID
811807
assert isinstance(uuid, UUID)
812808

813-
ts = (uuid.time - 0x01b21dd213814000) / 1e7 # back to a timestamp
809+
ts = (uuid.time - 0x01b21dd213814000) / 1e7 # back to a timestamp
814810
new_dt = datetime.fromtimestamp(ts, tz=timezone.utc).replace(tzinfo=None)
815811

816812
# checks that we created a UUID1 with the proper timestamp

tests/integration/standard/test_metadata.py

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1087,14 +1087,6 @@ def test_export_keyspace_schema_udts(self):
10871087
Test udt exports
10881088
"""
10891089

1090-
if PROTOCOL_VERSION < 3:
1091-
raise unittest.SkipTest(
1092-
"Protocol 3.0+ is required for UDT change events, currently testing against %r"
1093-
% (PROTOCOL_VERSION,))
1094-
1095-
if sys.version_info[0:2] != (2, 7):
1096-
raise unittest.SkipTest('This test compares static strings generated from dict items, which may change orders. Test with 2.7.')
1097-
10981090
cluster = TestCluster()
10991091
session = cluster.connect()
11001092

@@ -1591,7 +1583,7 @@ def test_function_no_parameters(self):
15911583

15921584
with self.VerifiedFunction(self, **kwargs) as vf:
15931585
fn_meta = self.keyspace_function_meta[vf.signature]
1594-
self.assertRegex(fn_meta.as_cql_query(), "CREATE FUNCTION.*%s\(\) .*" % kwargs['name'])
1586+
self.assertRegex(fn_meta.as_cql_query(), r"CREATE FUNCTION.*%s\(\) .*" % kwargs['name'])
15951587

15961588
def test_functions_follow_keyspace_alter(self):
15971589
"""
@@ -1639,12 +1631,12 @@ def test_function_cql_called_on_null(self):
16391631
kwargs['called_on_null_input'] = True
16401632
with self.VerifiedFunction(self, **kwargs) as vf:
16411633
fn_meta = self.keyspace_function_meta[vf.signature]
1642-
self.assertRegex(fn_meta.as_cql_query(), "CREATE FUNCTION.*\) CALLED ON NULL INPUT RETURNS .*")
1634+
self.assertRegex(fn_meta.as_cql_query(), r"CREATE FUNCTION.*\) CALLED ON NULL INPUT RETURNS .*")
16431635

16441636
kwargs['called_on_null_input'] = False
16451637
with self.VerifiedFunction(self, **kwargs) as vf:
16461638
fn_meta = self.keyspace_function_meta[vf.signature]
1647-
self.assertRegex(fn_meta.as_cql_query(), "CREATE FUNCTION.*\) RETURNS NULL ON NULL INPUT RETURNS .*")
1639+
self.assertRegex(fn_meta.as_cql_query(), r"CREATE FUNCTION.*\) RETURNS NULL ON NULL INPUT RETURNS .*")
16481640

16491641

16501642
class AggregateMetadata(FunctionTest):

tests/unit/advanced/test_insights.py

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818
import unittest
1919

2020
import logging
21-
import sys
2221
from unittest.mock import sentinel
2322

2423
from cassandra import ConsistencyLevel
@@ -32,7 +31,6 @@
3231
from cassandra.datastax.graph.query import GraphOptions
3332
from cassandra.datastax.insights.registry import insights_registry
3433
from cassandra.datastax.insights.serializers import initialize_registry
35-
from cassandra.datastax.insights.util import namespace
3634
from cassandra.policies import (
3735
RoundRobinPolicy,
3836
LoadBalancingPolicy,
@@ -63,8 +61,7 @@ class NoConfAsDict(object):
6361
obj = NoConfAsDict()
6462

6563
ns = 'tests.unit.advanced.test_insights'
66-
if sys.version_info > (3,):
67-
ns += '.TestGetConfig.test_invalid_object.<locals>'
64+
ns += '.TestGetConfig.test_invalid_object.<locals>'
6865

6966
# no default
7067
# ... as a policy
@@ -102,6 +99,7 @@ def superclass_sentinel_serializer(obj):
10299
self.assertIs(insights_registry.serialize(SubclassSentinel(), default=object()),
103100
sentinel.serialized_superclass)
104101

102+
105103
class TestConfigAsDict(unittest.TestCase):
106104

107105
# graph/query.py
@@ -253,35 +251,35 @@ def test_constant_reconnection_policy(self):
253251
self.assertEqual(
254252
insights_registry.serialize(ConstantReconnectionPolicy(3, 200)),
255253
{'type': 'ConstantReconnectionPolicy',
256-
'namespace': 'cassandra.policies',
257-
'options': {'delay': 3, 'max_attempts': 200}
254+
'namespace': 'cassandra.policies',
255+
'options': {'delay': 3, 'max_attempts': 200}
258256
}
259257
)
260258

261259
def test_exponential_reconnection_policy(self):
262260
self.assertEqual(
263261
insights_registry.serialize(ExponentialReconnectionPolicy(4, 100, 10)),
264262
{'type': 'ExponentialReconnectionPolicy',
265-
'namespace': 'cassandra.policies',
266-
'options': {'base_delay': 4, 'max_delay': 100, 'max_attempts': 10}
263+
'namespace': 'cassandra.policies',
264+
'options': {'base_delay': 4, 'max_delay': 100, 'max_attempts': 10}
267265
}
268266
)
269267

270268
def test_retry_policy(self):
271269
self.assertEqual(
272270
insights_registry.serialize(RetryPolicy()),
273271
{'type': 'RetryPolicy',
274-
'namespace': 'cassandra.policies',
275-
'options': {}
272+
'namespace': 'cassandra.policies',
273+
'options': {}
276274
}
277275
)
278276

279277
def test_spec_exec_policy(self):
280278
self.assertEqual(
281279
insights_registry.serialize(SpeculativeExecutionPolicy()),
282280
{'type': 'SpeculativeExecutionPolicy',
283-
'namespace': 'cassandra.policies',
284-
'options': {}
281+
'namespace': 'cassandra.policies',
282+
'options': {}
285283
}
286284
)
287285

0 commit comments

Comments
 (0)