Skip to content

Commit f176012

Browse files
committed
Remove compatibility code for Python < 3.7
1 parent f519826 commit f176012

File tree

16 files changed

+60
-162
lines changed

16 files changed

+60
-162
lines changed

aws_xray_sdk/core/__init__.py

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,8 @@
1+
from .async_recorder import AsyncAWSXRayRecorder
2+
from .patcher import patch, patch_all
13
from .recorder import AWSXRayRecorder
2-
from .patcher import patch_all, patch
3-
from .utils.compat import PY35
44

5-
6-
if not PY35:
7-
xray_recorder = AWSXRayRecorder()
8-
else:
9-
from .async_recorder import AsyncAWSXRayRecorder
10-
xray_recorder = AsyncAWSXRayRecorder()
5+
xray_recorder = AsyncAWSXRayRecorder()
116

127
__all__ = [
138
'patch',

aws_xray_sdk/core/async_context.py

Lines changed: 4 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,8 @@
11
import asyncio
2-
import sys
32
import copy
43

54
from .context import Context as _Context
65

7-
_GTE_PY37 = sys.version_info.major == 3 and sys.version_info.minor >= 7
8-
96

107
class AsyncContext(_Context):
118
"""
@@ -51,10 +48,7 @@ def __setattr__(self, name, value):
5148

5249
else:
5350
# Set task local attributes
54-
if _GTE_PY37:
55-
task = asyncio.current_task(loop=self._loop)
56-
else:
57-
task = asyncio.Task.current_task(loop=self._loop)
51+
task = asyncio.current_task(loop=self._loop)
5852
if task is None:
5953
return None
6054

@@ -68,10 +62,7 @@ def __getattribute__(self, item):
6862
# Return references to local objects
6963
return object.__getattribute__(self, item)
7064

71-
if _GTE_PY37:
72-
task = asyncio.current_task(loop=self._loop)
73-
else:
74-
task = asyncio.Task.current_task(loop=self._loop)
65+
task = asyncio.current_task(loop=self._loop)
7566
if task is None:
7667
return None
7768

@@ -82,10 +73,7 @@ def __getattribute__(self, item):
8273

8374
def clear(self):
8475
# If were in a task, clear the context dictionary
85-
if _GTE_PY37:
86-
task = asyncio.current_task(loop=self._loop)
87-
else:
88-
task = asyncio.Task.current_task(loop=self._loop)
76+
task = asyncio.current_task(loop=self._loop)
8977
if task is not None and hasattr(task, 'context'):
9078
task.context.clear()
9179

@@ -104,10 +92,7 @@ def task_factory(loop, coro):
10492
del task._source_traceback[-1] # flake8: noqa
10593

10694
# Share context with new task if possible
107-
if _GTE_PY37:
108-
current_task = asyncio.current_task(loop=loop)
109-
else:
110-
current_task = asyncio.Task.current_task(loop=loop)
95+
current_task = asyncio.current_task(loop=loop)
11196
if current_task is not None and hasattr(current_task, 'context'):
11297
if current_task.context.get('entities'):
11398
# NOTE: (enowell) Because the `AWSXRayRecorder`'s `Context` decides

aws_xray_sdk/core/patcher.py

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import wrapt
99

1010
from aws_xray_sdk import global_sdk_config
11-
from .utils.compat import PY2, is_classmethod, is_instance_method
11+
from .utils.compat import is_classmethod, is_instance_method
1212

1313
log = logging.getLogger(__name__)
1414

@@ -55,17 +55,14 @@ def patch_all(double_patch=False):
5555

5656
def _is_valid_import(module):
5757
module = module.replace('.', '/')
58-
if PY2:
59-
return bool(pkgutil.get_loader(module))
60-
else:
61-
realpath = os.path.realpath(module)
62-
is_module = os.path.isdir(realpath) and (
63-
os.path.isfile('{}/__init__.py'.format(module)) or os.path.isfile('{}/__init__.pyc'.format(module))
64-
)
65-
is_file = not is_module and (
66-
os.path.isfile('{}.py'.format(module)) or os.path.isfile('{}.pyc'.format(module))
67-
)
68-
return is_module or is_file
58+
realpath = os.path.realpath(module)
59+
is_module = os.path.isdir(realpath) and (
60+
os.path.isfile('{}/__init__.py'.format(module)) or os.path.isfile('{}/__init__.pyc'.format(module))
61+
)
62+
is_file = not is_module and (
63+
os.path.isfile('{}.py'.format(module)) or os.path.isfile('{}.pyc'.format(module))
64+
)
65+
return is_module or is_file
6966

7067

7168
def patch(modules_to_patch, raise_errors=True, ignore_module_patterns=None):

aws_xray_sdk/core/plugins/ec2_plugin.py

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,6 @@
11
import json
22
import logging
3-
4-
from aws_xray_sdk.core.utils.compat import PY2
5-
6-
if PY2:
7-
from future.standard_library import install_aliases
8-
install_aliases()
9-
10-
from urllib.request import urlopen, Request
3+
from urllib.request import Request, urlopen
114

125
log = logging.getLogger(__name__)
136

aws_xray_sdk/core/sampling/connector.py

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
from .sampling_rule import SamplingRule
1111
from aws_xray_sdk.core.models.dummy_entities import DummySegment
1212
from aws_xray_sdk.core.context import Context
13-
from aws_xray_sdk.core.utils.compat import PY2
1413

1514

1615
class ServiceConnector:
@@ -137,16 +136,8 @@ def _dt_to_epoch(self, dt):
137136
"""
138137
Convert a offset-aware datetime to POSIX time.
139138
"""
140-
if PY2:
141-
# The input datetime is from botocore unmarshalling and it is
142-
# offset-aware so the timedelta of subtracting this time
143-
# to 01/01/1970 using the same tzinfo gives us
144-
# Unix Time (also known as POSIX Time).
145-
time_delta = dt - datetime(1970, 1, 1).replace(tzinfo=dt.tzinfo)
146-
return int(time_delta.total_seconds())
147-
else:
148-
# Added in python 3.3+ and directly returns POSIX time.
149-
return int(dt.timestamp())
139+
# Added in python 3.3+ and directly returns POSIX time.
140+
return int(dt.timestamp())
150141

151142
def _is_rule_valid(self, record):
152143
# We currently only handle v1 sampling rules.

aws_xray_sdk/core/utils/compat.py

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,7 @@
11
import inspect
2-
import sys
32

4-
5-
PY2 = sys.version_info < (3,)
6-
PY35 = sys.version_info >= (3, 5)
7-
8-
if PY2:
9-
annotation_value_types = (int, long, float, bool, str, unicode) # noqa: F821
10-
string_types = basestring # noqa: F821
11-
else:
12-
annotation_value_types = (int, float, bool, str)
13-
string_types = str
3+
annotation_value_types = (int, float, bool, str)
4+
string_types = str
145

156

167
def is_classmethod(func):

aws_xray_sdk/ext/httplib/patch.py

Lines changed: 7 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,17 @@
1-
from collections import namedtuple
2-
import sys
3-
import wrapt
41
import fnmatch
2+
from collections import namedtuple
3+
54
import urllib3.connection
5+
import wrapt
66

77
from aws_xray_sdk.core import xray_recorder
8-
from aws_xray_sdk.core.models import http
98
from aws_xray_sdk.core.exceptions.exceptions import SegmentNotFoundException
9+
from aws_xray_sdk.core.models import http
1010
from aws_xray_sdk.core.patcher import _PATCHED_MODULES
11-
from aws_xray_sdk.ext.util import inject_trace_header, strip_url, unwrap, get_hostname
12-
13-
if sys.version_info >= (3, 0, 0):
14-
PY2 = False
15-
httplib_client_module = 'http.client'
16-
import http.client as httplib
17-
else:
18-
PY2 = True
19-
httplib_client_module = 'httplib'
20-
import httplib
11+
from aws_xray_sdk.ext.util import get_hostname, inject_trace_header, strip_url, unwrap
2112

13+
httplib_client_module = 'http.client'
14+
import http.client as httplib
2215

2316
_XRAY_PROP = '_xray_prop'
2417
_XRay_Data = namedtuple('xray_data', ['method', 'host', 'url'])
@@ -72,10 +65,6 @@ def http_response_processor(wrapped, instance, args, kwargs, return_value,
7265

7366

7467
def _xray_traced_http_getresponse(wrapped, instance, args, kwargs):
75-
if not PY2 and kwargs.get('buffering', False):
76-
# ignore py2 calls that fail as 'buffering` only exists in py2.
77-
return wrapped(*args, **kwargs)
78-
7968
xray_data = getattr(instance, _XRAY_PROP, None)
8069
if not xray_data:
8170
return wrapped(*args, **kwargs)

aws_xray_sdk/ext/sqlalchemy/util/decorators.py

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,12 @@
11
import re
22
import types
3+
from urllib.parse import urlparse, uses_netloc
4+
5+
from sqlalchemy.engine.base import Connection
36

47
from aws_xray_sdk.core import xray_recorder
58
from aws_xray_sdk.ext.util import strip_url
69

7-
from aws_xray_sdk.core.utils.compat import PY2
8-
9-
if PY2:
10-
from future.standard_library import install_aliases
11-
install_aliases()
12-
13-
from urllib.parse import urlparse, uses_netloc
14-
from sqlalchemy.engine.base import Connection
15-
1610

1711
def decorate_all_functions(function_decorator):
1812
def decorator(cls):

aws_xray_sdk/ext/sqlalchemy_core/patch.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,15 @@
11
import logging
22
import sys
3-
4-
if sys.version_info >= (3, 0, 0):
5-
from urllib.parse import urlparse, uses_netloc
6-
else:
7-
from urlparse import urlparse, uses_netloc
3+
from urllib.parse import urlparse, uses_netloc
84

95
import wrapt
6+
from sqlalchemy.sql.expression import ClauseElement
107

118
from aws_xray_sdk.core import xray_recorder
129
from aws_xray_sdk.core.patcher import _PATCHED_MODULES
1310
from aws_xray_sdk.core.utils import stacktrace
1411
from aws_xray_sdk.ext.util import unwrap
1512

16-
from sqlalchemy.sql.expression import ClauseElement
17-
1813

1914
def _sql_meta(engine_instance, args):
2015
try:

aws_xray_sdk/ext/util.py

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,10 @@
11
import re
2-
3-
from aws_xray_sdk.core.models.trace_header import TraceHeader
4-
from aws_xray_sdk.core.models import http
2+
from urllib.parse import urlparse
53

64
import wrapt
7-
import sys
8-
9-
if sys.version_info.major >= 3: # Python 3 and above
10-
from urllib.parse import urlparse
11-
else: # Python 2 and below
12-
from urlparse import urlparse
135

6+
from aws_xray_sdk.core.models import http
7+
from aws_xray_sdk.core.models.trace_header import TraceHeader
148

159
first_cap_re = re.compile('(.)([A-Z][a-z]+)')
1610
all_cap_re = re.compile('([a-z0-9])([A-Z])')

tests/ext/aiohttp/test_middleware.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,18 @@
55
"""
66
import asyncio
77
import sys
8-
from aws_xray_sdk import global_sdk_config
9-
try:
10-
from unittest.mock import patch
11-
except ImportError:
12-
# NOTE: Python 2 dependency
13-
from mock import patch
8+
from unittest.mock import patch
149

10+
import pytest
1511
from aiohttp import web
1612
from aiohttp.web_exceptions import HTTPUnauthorized
17-
import pytest
1813

19-
from aws_xray_sdk.core.emitters.udp_emitter import UDPEmitter
14+
from aws_xray_sdk import global_sdk_config
2015
from aws_xray_sdk.core.async_context import AsyncContext
16+
from aws_xray_sdk.core.emitters.udp_emitter import UDPEmitter
2117
from aws_xray_sdk.core.models import http
22-
from tests.util import get_new_stubbed_recorder
2318
from aws_xray_sdk.ext.aiohttp.middleware import middleware
19+
from tests.util import get_new_stubbed_recorder
2420

2521

2622
class CustomStubbedEmitter(UDPEmitter):

tests/ext/django/test_settings.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,11 @@
1-
try:
2-
from unittest import mock
3-
except ImportError:
4-
# NOTE: Python 2 dependency
5-
import mock
1+
from unittest import mock
62

73
import django
8-
from aws_xray_sdk import global_sdk_config
9-
from django.test import TestCase, override_settings
10-
from django.conf import settings
114
from django.apps import apps
5+
from django.conf import settings
6+
from django.test import TestCase, override_settings
127

8+
from aws_xray_sdk import global_sdk_config
139
from aws_xray_sdk.core import xray_recorder
1410
from aws_xray_sdk.core.sampling.sampler import LocalSampler
1511

tests/ext/httplib/test_httplib.py

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,11 @@
1+
import http.client as httplib
2+
from urllib.parse import urlparse
3+
14
import pytest
2-
import sys
35

4-
from aws_xray_sdk.core import patch
5-
from aws_xray_sdk.core import xray_recorder
6+
from aws_xray_sdk.core import patch, xray_recorder
67
from aws_xray_sdk.core.context import Context
7-
from aws_xray_sdk.ext.util import strip_url, get_hostname
8-
9-
if sys.version_info >= (3, 0, 0):
10-
import http.client as httplib
11-
from urllib.parse import urlparse
12-
else:
13-
import httplib
14-
from urlparse import urlparse
15-
8+
from aws_xray_sdk.ext.util import get_hostname, strip_url
169

1710
# httpbin.org is created by the same author of requests to make testing http easy.
1811
BASE_URL = 'httpbin.org'
@@ -25,7 +18,7 @@ def construct_ctx():
2518
so that later subsegment can be attached. After each test run
2619
it cleans up context storage again.
2720
"""
28-
from aws_xray_sdk.ext.httplib import unpatch, reset_ignored
21+
from aws_xray_sdk.ext.httplib import reset_ignored, unpatch
2922

3023
patch(('httplib',))
3124
xray_recorder.configure(service='test', sampling=False, context=Context())

tests/test_plugins.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
1+
from unittest.mock import patch
2+
13
from aws_xray_sdk.core.plugins.utils import get_plugin_modules
2-
try:
3-
from unittest.mock import patch
4-
except ImportError:
5-
# NOTE: Python 2 dependency
6-
from mock import patch
74

85
supported_plugins = (
96
'ec2_plugin',

0 commit comments

Comments
 (0)