Skip to content

Commit 3b1a622

Browse files
refactor: remove unnecessary python 2 deps/syntax (#385)
* python version update * convert to f-strings * remove redundant super params * swap deprecated threading method * remove unnecessary py2 deps * fix abstract class * remove py2 wrapper func/format * remove py2 unittest patch * remove redundant inherit object * fix event queue test timing issue
1 parent 42f6663 commit 3b1a622

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

53 files changed

+455
-526
lines changed

optimizely/bucketer.py

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
GROUP_POLICIES = ['random']
2525

2626

27-
class Bucketer(object):
27+
class Bucketer:
2828
""" Optimizely bucketing algorithm that evenly distributes visitors. """
2929

3030
def __init__(self):
@@ -72,9 +72,8 @@ def find_bucket(self, project_config, bucketing_id, parent_id, traffic_allocatio
7272
"""
7373
bucketing_key = BUCKETING_ID_TEMPLATE.format(bucketing_id=bucketing_id, parent_id=parent_id)
7474
bucketing_number = self._generate_bucket_value(bucketing_key)
75-
message = 'Assigned bucket %s to user with bucketing ID "%s".' % (bucketing_number, bucketing_id)
7675
project_config.logger.debug(
77-
message
76+
f'Assigned bucket {bucketing_number} to user with bucketing ID "{bucketing_id}".'
7877
)
7978

8079
for traffic_allocation in traffic_allocations:
@@ -115,24 +114,19 @@ def bucket(self, project_config, experiment, user_id, bucketing_id):
115114
)
116115

117116
if not user_experiment_id:
118-
message = 'User "%s" is in no experiment.' % user_id
117+
message = f'User "{user_id}" is in no experiment.'
119118
project_config.logger.info(message)
120119
decide_reasons.append(message)
121120
return None, decide_reasons
122121

123122
if user_experiment_id != experiment.id:
124-
message = 'User "%s" is not in experiment "%s" of group %s.' \
125-
% (user_id, experiment.key, experiment.groupId)
126-
project_config.logger.info(
127-
message
128-
)
123+
message = f'User "{user_id}" is not in experiment "{experiment.key}" of group {experiment.groupId}.'
124+
project_config.logger.info(message)
129125
decide_reasons.append(message)
130126
return None, decide_reasons
131127

132-
message = 'User "%s" is in experiment %s of group %s.' % (user_id, experiment.key, experiment.groupId)
133-
project_config.logger.info(
134-
message
135-
)
128+
message = f'User "{user_id}" is in experiment {experiment.key} of group {experiment.groupId}.'
129+
project_config.logger.info(message)
136130
decide_reasons.append(message)
137131

138132
# Bucket user if not in white-list and in group (if any)

optimizely/config_manager.py

Lines changed: 22 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
# See the License for the specific language governing permissions and
1212
# limitations under the License.
1313

14-
import abc
14+
from abc import ABC, abstractmethod
1515
import numbers
1616
import requests
1717
import threading
@@ -28,8 +28,6 @@
2828
from .helpers import validator
2929
from .optimizely_config import OptimizelyConfigService
3030

31-
ABC = abc.ABCMeta('ABC', (object,), {'__slots__': ()})
32-
3331

3432
class BaseConfigManager(ABC):
3533
""" Base class for Optimizely's config manager. """
@@ -62,7 +60,7 @@ def _validate_instantiation_options(self):
6260
if not validator.is_notification_center_valid(self.notification_center):
6361
raise optimizely_exceptions.InvalidInputException(enums.Errors.INVALID_INPUT.format('notification_center'))
6462

65-
@abc.abstractmethod
63+
@abstractmethod
6664
def get_config(self):
6765
""" Get config for use by optimizely.Optimizely.
6866
The config should be an instance of project_config.ProjectConfig."""
@@ -86,7 +84,7 @@ def __init__(
8684
validation upon object invocation. By default
8785
JSON schema validation will be performed.
8886
"""
89-
super(StaticConfigManager, self).__init__(
87+
super().__init__(
9088
logger=logger, error_handler=error_handler, notification_center=notification_center,
9189
)
9290
self._config = None
@@ -134,7 +132,7 @@ def _set_config(self, datafile):
134132
self.notification_center.send_notifications(enums.NotificationTypes.OPTIMIZELY_CONFIG_UPDATE)
135133
self.logger.debug(
136134
'Received new datafile and updated config. '
137-
'Old revision number: {}. New revision number: {}.'.format(previous_revision, config.get_revision())
135+
f'Old revision number: {previous_revision}. New revision number: {config.get_revision()}.'
138136
)
139137

140138
def get_config(self):
@@ -186,7 +184,7 @@ def __init__(
186184
187185
"""
188186
self._config_ready_event = threading.Event()
189-
super(PollingConfigManager, self).__init__(
187+
super().__init__(
190188
datafile=datafile,
191189
logger=logger,
192190
error_handler=error_handler,
@@ -200,7 +198,7 @@ def __init__(
200198
self.set_blocking_timeout(blocking_timeout)
201199
self.last_modified = None
202200
self._polling_thread = threading.Thread(target=self._run)
203-
self._polling_thread.setDaemon(True)
201+
self._polling_thread.daemon = True
204202
self._polling_thread.start()
205203

206204
@staticmethod
@@ -231,7 +229,7 @@ def get_datafile_url(sdk_key, url, url_template):
231229
return url_template.format(sdk_key=sdk_key)
232230
except (AttributeError, KeyError):
233231
raise optimizely_exceptions.InvalidInputException(
234-
'Invalid url_template {} provided.'.format(url_template)
232+
f'Invalid url_template {url_template} provided.'
235233
)
236234

237235
return url
@@ -243,7 +241,7 @@ def _set_config(self, datafile):
243241
datafile: JSON string representing the Optimizely project.
244242
"""
245243
if datafile or self._config_ready_event.is_set():
246-
super(PollingConfigManager, self)._set_config(datafile=datafile)
244+
super()._set_config(datafile=datafile)
247245
self._config_ready_event.set()
248246

249247
def get_config(self):
@@ -265,19 +263,18 @@ def set_update_interval(self, update_interval):
265263
"""
266264
if update_interval is None:
267265
update_interval = enums.ConfigManager.DEFAULT_UPDATE_INTERVAL
268-
self.logger.debug('Setting config update interval to default value {}.'.format(update_interval))
266+
self.logger.debug(f'Setting config update interval to default value {update_interval}.')
269267

270268
if not isinstance(update_interval, (int, float)):
271269
raise optimizely_exceptions.InvalidInputException(
272-
'Invalid update_interval "{}" provided.'.format(update_interval)
270+
f'Invalid update_interval "{update_interval}" provided.'
273271
)
274272

275273
# If polling interval is less than or equal to 0 then set it to default update interval.
276274
if update_interval <= 0:
277275
self.logger.debug(
278-
'update_interval value {} too small. Defaulting to {}'.format(
279-
update_interval, enums.ConfigManager.DEFAULT_UPDATE_INTERVAL
280-
)
276+
f'update_interval value {update_interval} too small. '
277+
f'Defaulting to {enums.ConfigManager.DEFAULT_UPDATE_INTERVAL}'
281278
)
282279
update_interval = enums.ConfigManager.DEFAULT_UPDATE_INTERVAL
283280

@@ -291,19 +288,18 @@ def set_blocking_timeout(self, blocking_timeout):
291288
"""
292289
if blocking_timeout is None:
293290
blocking_timeout = enums.ConfigManager.DEFAULT_BLOCKING_TIMEOUT
294-
self.logger.debug('Setting config blocking timeout to default value {}.'.format(blocking_timeout))
291+
self.logger.debug(f'Setting config blocking timeout to default value {blocking_timeout}.')
295292

296293
if not isinstance(blocking_timeout, (numbers.Integral, float)):
297294
raise optimizely_exceptions.InvalidInputException(
298-
'Invalid blocking timeout "{}" provided.'.format(blocking_timeout)
295+
f'Invalid blocking timeout "{blocking_timeout}" provided.'
299296
)
300297

301298
# If blocking timeout is less than 0 then set it to default blocking timeout.
302299
if blocking_timeout < 0:
303300
self.logger.debug(
304-
'blocking timeout value {} too small. Defaulting to {}'.format(
305-
blocking_timeout, enums.ConfigManager.DEFAULT_BLOCKING_TIMEOUT
306-
)
301+
f'blocking timeout value {blocking_timeout} too small. '
302+
f'Defaulting to {enums.ConfigManager.DEFAULT_BLOCKING_TIMEOUT}'
307303
)
308304
blocking_timeout = enums.ConfigManager.DEFAULT_BLOCKING_TIMEOUT
309305

@@ -326,12 +322,12 @@ def _handle_response(self, response):
326322
try:
327323
response.raise_for_status()
328324
except requests_exceptions.RequestException as err:
329-
self.logger.error('Fetching datafile from {} failed. Error: {}'.format(self.datafile_url, str(err)))
325+
self.logger.error(f'Fetching datafile from {self.datafile_url} failed. Error: {err}')
330326
return
331327

332328
# Leave datafile and config unchanged if it has not been modified.
333329
if response.status_code == http_status_codes.not_modified:
334-
self.logger.debug('Not updating config as datafile has not updated since {}.'.format(self.last_modified))
330+
self.logger.debug(f'Not updating config as datafile has not updated since {self.last_modified}.')
335331
return
336332

337333
self.set_last_modified(response.headers)
@@ -349,7 +345,7 @@ def fetch_datafile(self):
349345
self.datafile_url, headers=request_headers, timeout=enums.ConfigManager.REQUEST_TIMEOUT,
350346
)
351347
except requests_exceptions.RequestException as err:
352-
self.logger.error('Fetching datafile from {} failed. Error: {}'.format(self.datafile_url, str(err)))
348+
self.logger.error(f'Fetching datafile from {self.datafile_url} failed. Error: {err}')
353349
return
354350

355351
self._handle_response(response)
@@ -367,7 +363,7 @@ def _run(self):
367363
time.sleep(self.update_interval)
368364
except (OSError, OverflowError) as err:
369365
self.logger.error(
370-
'Error in time.sleep. ' 'Provided update_interval value may be too big. Error: {}'.format(str(err))
366+
f'Error in time.sleep. Provided update_interval value may be too big. Error: {err}'
371367
)
372368
raise
373369

@@ -396,7 +392,7 @@ def __init__(
396392
**kwargs: Refer to keyword arguments descriptions in PollingConfigManager.
397393
"""
398394
self._set_datafile_access_token(datafile_access_token)
399-
super(AuthDatafilePollingConfigManager, self).__init__(*args, **kwargs)
395+
super().__init__(*args, **kwargs)
400396

401397
def _set_datafile_access_token(self, datafile_access_token):
402398
""" Checks for valid access token input and sets it. """
@@ -421,7 +417,7 @@ def fetch_datafile(self):
421417
self.datafile_url, headers=request_headers, timeout=enums.ConfigManager.REQUEST_TIMEOUT,
422418
)
423419
except requests_exceptions.RequestException as err:
424-
self.logger.error('Fetching datafile from {} failed. Error: {}'.format(self.datafile_url, str(err)))
420+
self.logger.error(f'Fetching datafile from {self.datafile_url} failed. Error: {err}')
425421
return
426422

427423
self._handle_response(response)

optimizely/decision/optimizely_decide_option.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
# limitations under the License.
1313

1414

15-
class OptimizelyDecideOption(object):
15+
class OptimizelyDecideOption:
1616
DISABLE_DECISION_EVENT = 'DISABLE_DECISION_EVENT'
1717
ENABLED_FLAGS_ONLY = 'ENABLED_FLAGS_ONLY'
1818
IGNORE_USER_PROFILE_SERVICE = 'IGNORE_USER_PROFILE_SERVICE'

optimizely/decision/optimizely_decision.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
# limitations under the License.
1313

1414

15-
class OptimizelyDecision(object):
15+
class OptimizelyDecision:
1616
def __init__(self, variation_key=None, enabled=None,
1717
variables=None, rule_key=None, flag_key=None, user_context=None, reasons=None):
1818
self.variation_key = variation_key

optimizely/decision/optimizely_decision_message.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
# limitations under the License.
1313

1414

15-
class OptimizelyDecisionMessage(object):
15+
class OptimizelyDecisionMessage:
1616
SDK_NOT_READY = 'Optimizely SDK not configured properly yet.'
1717
FLAG_KEY_INVALID = 'No flag was found for key "{}".'
1818
VARIABLE_VALUE_INVALID = 'Variable value for key "{}" is invalid or wrong type.'

0 commit comments

Comments
 (0)