Remove six

Remove six Replace the following items with Python 3 style code.
- six.moves
- six.StringIO
- six.add_metaclass
- six.string_types
- six.binary_type
- six.text_type
- six.integer_types
- six.PY3
- six.PY2
- six.iterkeys

Change-Id: Id9f2076be1a6a2d99db5acb682df8bebe893de36
This commit is contained in:
wangzihao 2020-10-12 19:39:10 +08:00
parent 2794b9828c
commit adc39e86ac
15 changed files with 27 additions and 40 deletions

View File

@ -39,8 +39,7 @@ Five ways to add a new trace point.
def _traced_only_if_trace_private_true(self): def _traced_only_if_trace_private_true(self):
pass pass
@six.add_metaclass(profiler.TracedMeta) class RpcManagerClass(object, metaclass=profiler.TracedMeta):
class RpcManagerClass(object):
__trace_args__ = {'name': 'rpc', __trace_args__ = {'name': 'rpc',
'info': None, 'info': None,
'hide_args': False, 'hide_args': False,

View File

@ -15,7 +15,6 @@ pymongo===3.0.2
redis===2.10.0 redis===2.10.0
reno==3.1.0 reno==3.1.0
requests===2.14.2 requests===2.14.2
six===1.10.0
Sphinx===2.0.0 Sphinx===2.0.0
stestr==2.0.0 stestr==2.0.0
testtools===2.2.0 testtools===2.2.0

View File

@ -22,7 +22,6 @@ import uuid
from oslo_utils import secretutils from oslo_utils import secretutils
from oslo_utils import uuidutils from oslo_utils import uuidutils
import six
def split(text, strip=True): def split(text, strip=True):
@ -32,7 +31,7 @@ def split(text, strip=True):
""" """
if isinstance(text, (tuple, list)): if isinstance(text, (tuple, list)):
return text return text
if not isinstance(text, six.string_types): if not isinstance(text, str):
raise TypeError("Unknown how to split '%s': %s" % (text, type(text))) raise TypeError("Unknown how to split '%s': %s" % (text, type(text)))
if strip: if strip:
return [t.strip() for t in text.split(",") if t.strip()] return [t.strip() for t in text.split(",") if t.strip()]
@ -45,9 +44,9 @@ def binary_encode(text, encoding="utf-8"):
Does nothing if text not unicode string. Does nothing if text not unicode string.
""" """
if isinstance(text, six.binary_type): if isinstance(text, bytes):
return text return text
elif isinstance(text, six.text_type): elif isinstance(text, str):
return text.encode(encoding) return text.encode(encoding)
else: else:
raise TypeError("Expected binary or string type") raise TypeError("Expected binary or string type")
@ -58,9 +57,9 @@ def binary_decode(data, encoding="utf-8"):
Does nothing if data is already unicode string. Does nothing if data is already unicode string.
""" """
if isinstance(data, six.binary_type): if isinstance(data, bytes):
return data.decode(encoding) return data.decode(encoding)
elif isinstance(data, six.text_type): elif isinstance(data, str):
return data return data
else: else:
raise TypeError("Expected binary or string type") raise TypeError("Expected binary or string type")
@ -154,7 +153,7 @@ def import_modules_from_package(package):
def shorten_id(span_id): def shorten_id(span_id):
"""Convert from uuid4 to 64 bit id for OpenTracing""" """Convert from uuid4 to 64 bit id for OpenTracing"""
int64_max = (1 << 64) - 1 int64_max = (1 << 64) - 1
if isinstance(span_id, six.integer_types): if isinstance(span_id, int):
return span_id & int64_max return span_id & int64_max
try: try:
short_id = uuid.UUID(span_id).int & int64_max short_id = uuid.UUID(span_id).int & int64_max

View File

@ -19,7 +19,6 @@ import os
from oslo_utils import encodeutils from oslo_utils import encodeutils
from oslo_utils import uuidutils from oslo_utils import uuidutils
import prettytable import prettytable
import six
from osprofiler.cmd import cliutils from osprofiler.cmd import cliutils
from osprofiler.drivers import base from osprofiler.drivers import base
@ -188,7 +187,4 @@ class TraceCommands(BaseCommand):
for trace in traces: for trace in traces:
row = [trace[field] for field in fields] row = [trace[field] for field in fields]
pretty_table.add_row(row) pretty_table.add_row(row)
if six.PY3: print(encodeutils.safe_encode(pretty_table.get_string()).decode())
print(encodeutils.safe_encode(pretty_table.get_string()).decode())
else:
print(encodeutils.safe_encode(pretty_table.get_string()))

View File

@ -15,8 +15,7 @@
import datetime import datetime
import logging import logging
from urllib import parse as urlparse
import six.moves.urllib.parse as urlparse
from osprofiler import _utils from osprofiler import _utils

View File

@ -13,8 +13,9 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
from urllib import parse as parser
from oslo_config import cfg from oslo_config import cfg
import six.moves.urllib.parse as parser
from osprofiler.drivers import base from osprofiler.drivers import base
from osprofiler import exc from osprofiler import exc

View File

@ -16,10 +16,10 @@
import collections import collections
import datetime import datetime
import time import time
from urllib import parse as parser
from oslo_config import cfg from oslo_config import cfg
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
import six.moves.urllib.parse as parser
from osprofiler import _utils as utils from osprofiler import _utils as utils
from osprofiler.drivers import base from osprofiler.drivers import base

View File

@ -19,11 +19,11 @@ Classes to use VMware vRealize Log Insight as the trace data store.
import json import json
import logging as log import logging as log
from urllib import parse as urlparse
import netaddr import netaddr
from oslo_concurrency.lockutils import synchronized from oslo_concurrency.lockutils import synchronized
import requests import requests
import six.moves.urllib.parse as urlparse
from osprofiler.drivers import base from osprofiler.drivers import base
from osprofiler import exc from osprofiler import exc

View File

@ -14,10 +14,11 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
from urllib import parse as parser
from debtcollector import removals from debtcollector import removals
from oslo_config import cfg from oslo_config import cfg
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
import six.moves.urllib.parse as parser
from osprofiler.drivers import base from osprofiler.drivers import base
from osprofiler import exc from osprofiler import exc

View File

@ -364,7 +364,7 @@ def check_using_unicode(logical_line, filename):
if re.search(r"\bunicode\(", logical_line): if re.search(r"\bunicode\(", logical_line):
yield (0, "N353 'unicode' function is absent in python3. Please " yield (0, "N353 'unicode' function is absent in python3. Please "
"use 'six.text_type' instead.") "use 'str' instead.")
@core.flake8ext @core.flake8ext

View File

@ -22,7 +22,6 @@ import threading
from oslo_utils import reflection from oslo_utils import reflection
from oslo_utils import uuidutils from oslo_utils import uuidutils
import six
from osprofiler import _utils as utils from osprofiler import _utils as utils
from osprofiler import notifier from osprofiler import notifier
@ -161,7 +160,7 @@ def trace(name, info=None, hide_args=False, hide_result=True,
except Exception as ex: except Exception as ex:
stop_info = { stop_info = {
"etype": reflection.get_class_name(ex), "etype": reflection.get_class_name(ex),
"message": six.text_type(ex) "message": str(ex)
} }
raise raise
else: else:
@ -274,8 +273,7 @@ class TracedMeta(type):
Possible usage: Possible usage:
>>> @six.add_metaclass(profiler.TracedMeta) >>> class RpcManagerClass(object, metaclass=profiler.TracedMeta):
>>> class RpcManagerClass(object):
>>> __trace_args__ = {'name': 'rpc', >>> __trace_args__ = {'name': 'rpc',
>>> 'info': None, >>> 'info': None,
>>> 'hide_args': False, >>> 'hide_args': False,

View File

@ -13,13 +13,13 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import io
import json import json
import os import os
import sys import sys
from unittest import mock from unittest import mock
import ddt import ddt
import six
from osprofiler.cmd import shell from osprofiler.cmd import shell
from osprofiler import exc from osprofiler import exc
@ -43,7 +43,7 @@ class ShellTestCase(test.TestCase):
cmd = "trace show --connection-string redis:// %s" % self.TRACE_ID cmd = "trace show --connection-string redis:// %s" % self.TRACE_ID
return cmd if format_ is None else "%s --%s" % (cmd, format_) return cmd if format_ is None else "%s --%s" % (cmd, format_)
@mock.patch("sys.stdout", six.StringIO()) @mock.patch("sys.stdout", io.StringIO())
@mock.patch("osprofiler.cmd.shell.OSProfilerShell") @mock.patch("osprofiler.cmd.shell.OSProfilerShell")
def test_shell_main(self, mock_shell): def test_shell_main(self, mock_shell):
mock_shell.side_effect = exc.CommandError("some_message") mock_shell.side_effect = exc.CommandError("some_message")
@ -99,7 +99,7 @@ class ShellTestCase(test.TestCase):
} }
return notifications return notifications
@mock.patch("sys.stdout", six.StringIO()) @mock.patch("sys.stdout", io.StringIO())
@mock.patch("osprofiler.drivers.redis_driver.Redis.get_report") @mock.patch("osprofiler.drivers.redis_driver.Redis.get_report")
def test_trace_show_in_json(self, mock_get): def test_trace_show_in_json(self, mock_get):
notifications = self._create_mock_notifications() notifications = self._create_mock_notifications()
@ -110,7 +110,7 @@ class ShellTestCase(test.TestCase):
separators=(",", ": "),), separators=(",", ": "),),
sys.stdout.getvalue()) sys.stdout.getvalue())
@mock.patch("sys.stdout", six.StringIO()) @mock.patch("sys.stdout", io.StringIO())
@mock.patch("osprofiler.drivers.redis_driver.Redis.get_report") @mock.patch("osprofiler.drivers.redis_driver.Redis.get_report")
def test_trace_show_in_html(self, mock_get): def test_trace_show_in_html(self, mock_get):
notifications = self._create_mock_notifications() notifications = self._create_mock_notifications()
@ -139,7 +139,7 @@ class ShellTestCase(test.TestCase):
separators=(",", ": ")), separators=(",", ": ")),
sys.stdout.getvalue()) sys.stdout.getvalue())
@mock.patch("sys.stdout", six.StringIO()) @mock.patch("sys.stdout", io.StringIO())
@mock.patch("osprofiler.drivers.redis_driver.Redis.get_report") @mock.patch("osprofiler.drivers.redis_driver.Redis.get_report")
def test_trace_show_write_to_file(self, mock_get): def test_trace_show_write_to_file(self, mock_get):
notifications = self._create_mock_notifications() notifications = self._create_mock_notifications()

View File

@ -19,7 +19,6 @@ import datetime
import re import re
from unittest import mock from unittest import mock
import six
from osprofiler import profiler from osprofiler import profiler
from osprofiler.tests import test from osprofiler.tests import test
@ -462,7 +461,6 @@ class TraceClsDecoratorTestCase(test.TestCase):
# - and FakeTraceStatic.method4 in PY3 # - and FakeTraceStatic.method4 in PY3
"name": "name":
"osprofiler.tests.unit.test_profiler" "osprofiler.tests.unit.test_profiler"
".method4" if six.PY2 else
"osprofiler.tests.unit.test_profiler.FakeTraceStatic" "osprofiler.tests.unit.test_profiler.FakeTraceStatic"
".method4", ".method4",
"args": str((25,)), "args": str((25,)),
@ -490,8 +488,7 @@ class TraceClsDecoratorTestCase(test.TestCase):
self.assertFalse(mock_stop.called) self.assertFalse(mock_stop.called)
@six.add_metaclass(profiler.TracedMeta) class FakeTraceWithMetaclassBase(object, metaclass=profiler.TracedMeta):
class FakeTraceWithMetaclassBase(object):
__trace_args__ = {"name": "rpc", __trace_args__ = {"name": "rpc",
"info": {"a": 10}} "info": {"a": 10}}
@ -534,8 +531,8 @@ class TraceWithMetaclassTestCase(test.TestCase):
def test_no_name_exception(self): def test_no_name_exception(self):
def define_class_with_no_name(): def define_class_with_no_name():
@six.add_metaclass(profiler.TracedMeta) class FakeTraceWithMetaclassNoName(FakeTracedCls,
class FakeTraceWithMetaclassNoName(FakeTracedCls): metaclass=profiler.TracedMeta):
pass pass
self.assertRaises(TypeError, define_class_with_no_name, 1) self.assertRaises(TypeError, define_class_with_no_name, 1)

View File

@ -13,7 +13,6 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import six
import webob.dec import webob.dec
from osprofiler import _utils as utils from osprofiler import _utils as utils
@ -98,7 +97,7 @@ class WsgiMiddleware(object):
def _trace_is_valid(self, trace_info): def _trace_is_valid(self, trace_info):
if not isinstance(trace_info, dict): if not isinstance(trace_info, dict):
return False return False
trace_keys = set(six.iterkeys(trace_info)) trace_keys = set(trace_info.keys())
if not all(k in trace_keys for k in _REQUIRED_KEYS): if not all(k in trace_keys for k in _REQUIRED_KEYS):
return False return False
if trace_keys.difference(_REQUIRED_KEYS + _OPTIONAL_KEYS): if trace_keys.difference(_REQUIRED_KEYS + _OPTIONAL_KEYS):

View File

@ -4,6 +4,5 @@ oslo.serialization>=2.18.0 # Apache-2.0
oslo.utils>=3.33.0 # Apache-2.0 oslo.utils>=3.33.0 # Apache-2.0
PrettyTable<0.8,>=0.7.2 # BSD PrettyTable<0.8,>=0.7.2 # BSD
requests>=2.14.2 # Apache-2.0 requests>=2.14.2 # Apache-2.0
six>=1.10.0 # MIT
WebOb>=1.7.1 # MIT WebOb>=1.7.1 # MIT
importlib_metadata>=1.7.0;python_version<'3.8' # Apache-2.0 importlib_metadata>=1.7.0;python_version<'3.8' # Apache-2.0