Remove usage of six

With python3.x, classes can use 'metaclass=' instead of
'six.add_metaclass', 'six.iteritems' and 'six.iterkeys' can
be replaced by 'items' and 'keys', 'six.moves.urllib.parse'
can be replaced by 'urllib.parse', 'six.StringIO' and
'six.moves.cStringIO' can be replaced by 'io.StringIO',
'six.text_type' and 'six.string_type' are just 'str'.

Change-Id: I357968c6a1932856b1600f6c191966bc90cbc258
This commit is contained in:
zhanghao 2020-05-14 02:03:50 -04:00
parent 85ef7b7108
commit 3cfa54fa56
16 changed files with 34 additions and 52 deletions

View File

@ -97,7 +97,6 @@ requestsexceptions==1.2.0
rfc3986==0.3.1 rfc3986==0.3.1
Routes==2.3.1 Routes==2.3.1
simplejson==3.5.1 simplejson==3.5.1
six==1.10.0
snowballstemmer==1.2.1 snowballstemmer==1.2.1
statsd==3.2.1 statsd==3.2.1
stestr==2.0.0 stestr==2.0.0

View File

@ -14,7 +14,6 @@
# under the License. # under the License.
from oslo_utils import encodeutils from oslo_utils import encodeutils
import six
from neutronclient._i18n import _ from neutronclient._i18n import _
@ -40,7 +39,6 @@ def _safe_decode_dict(kwargs):
return kwargs return kwargs
@six.python_2_unicode_compatible
class NeutronException(Exception): class NeutronException(Exception):
"""Base Neutron Exception. """Base Neutron Exception.

View File

@ -14,7 +14,6 @@
# under the License. # under the License.
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
import six
from neutronclient._i18n import _ from neutronclient._i18n import _
from neutronclient.common import exceptions as exception from neutronclient.common import exceptions as exception
@ -48,7 +47,7 @@ class JSONDictSerializer(DictSerializer):
def default(self, data): def default(self, data):
def sanitizer(obj): def sanitizer(obj):
return six.text_type(obj) return str(obj)
return jsonutils.dumps(data, default=sanitizer) return jsonutils.dumps(data, default=sanitizer)

View File

@ -25,7 +25,6 @@ import os
from oslo_utils import encodeutils from oslo_utils import encodeutils
from oslo_utils import importutils from oslo_utils import importutils
import six
from neutronclient._i18n import _ from neutronclient._i18n import _
from neutronclient.common import exceptions from neutronclient.common import exceptions
@ -180,7 +179,7 @@ def http_log_req(_logger, args, kwargs):
else: else:
string_parts.append(' %s' % element) string_parts.append(' %s' % element)
for (key, value) in six.iteritems(kwargs['headers']): for (key, value) in kwargs['headers'].items():
if key in SENSITIVE_HEADERS: if key in SENSITIVE_HEADERS:
v = value.encode('utf-8') v = value.encode('utf-8')
h = hashlib.sha256(v) h = hashlib.sha256(v)
@ -205,7 +204,7 @@ def http_log_resp(_logger, resp, body):
def _safe_encode_without_obj(data): def _safe_encode_without_obj(data):
if isinstance(data, six.string_types): if isinstance(data, str):
return encodeutils.safe_encode(data) return encodeutils.safe_encode(data)
return data return data

View File

@ -25,7 +25,6 @@ from cliff import command
from cliff import lister from cliff import lister
from cliff import show from cliff import show
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
import six
from neutronclient._i18n import _ from neutronclient._i18n import _
from neutronclient.common import exceptions from neutronclient.common import exceptions
@ -261,12 +260,12 @@ def parse_args_to_dict(values_specs):
# Populate the parser with arguments # Populate the parser with arguments
_parser = argparse.ArgumentParser(add_help=False) _parser = argparse.ArgumentParser(add_help=False)
for opt, optspec in six.iteritems(_options): for opt, optspec in _options.items():
_parser.add_argument(opt, **optspec) _parser.add_argument(opt, **optspec)
_args = _parser.parse_args(_values_specs) _args = _parser.parse_args(_values_specs)
result_dict = {} result_dict = {}
for opt in six.iterkeys(_options): for opt in _options.keys():
_opt = opt.split('--', 2)[1] _opt = opt.split('--', 2)[1]
_opt = _opt.replace('-', '_') _opt = _opt.replace('-', '_')
_value = getattr(_args, _opt) _value = getattr(_args, _opt)
@ -285,7 +284,7 @@ def _merge_args(qCmd, parsed_args, _extra_values, value_specs):
@param values_specs: the unparsed unknown parts @param values_specs: the unparsed unknown parts
""" """
temp_values = _extra_values.copy() temp_values = _extra_values.copy()
for key, value in six.iteritems(temp_values): for key, value in temp_values.items():
if hasattr(parsed_args, key): if hasattr(parsed_args, key):
arg_value = getattr(parsed_args, key) arg_value = getattr(parsed_args, key)
if arg_value is not None and value is not None: if arg_value is not None and value is not None:
@ -321,8 +320,7 @@ class NeutronCommandMeta(abc.ABCMeta):
name, bases, cls_dict) name, bases, cls_dict)
@six.add_metaclass(NeutronCommandMeta) class NeutronCommand(command.Command, metaclass=NeutronCommandMeta):
class NeutronCommand(command.Command):
values_specs = [] values_specs = []
json_indent = None json_indent = None
@ -363,7 +361,7 @@ class NeutronCommand(command.Command):
def format_output_data(self, data): def format_output_data(self, data):
# Modify data to make it more readable # Modify data to make it more readable
if self.resource in data: if self.resource in data:
for k, v in six.iteritems(data[self.resource]): for k, v in data[self.resource].items():
if isinstance(v, list): if isinstance(v, list):
value = '\n'.join(jsonutils.dumps( value = '\n'.join(jsonutils.dumps(
i, indent=self.json_indent) if isinstance(i, dict) i, indent=self.json_indent) if isinstance(i, dict)
@ -425,7 +423,7 @@ class CreateCommand(NeutronCommand, show.ShowOne):
file=self.app.stdout) file=self.app.stdout)
else: else:
info = {'': ''} info = {'': ''}
return zip(*sorted(six.iteritems(info))) return zip(*sorted(info.items()))
class UpdateCommand(NeutronCommand): class UpdateCommand(NeutronCommand):
@ -825,6 +823,6 @@ class ShowCommand(NeutronCommand, show.ShowOne):
self.format_output_data(data) self.format_output_data(data)
resource = data[self.resource] resource = data[self.resource]
if self.resource in data: if self.resource in data:
return zip(*sorted(six.iteritems(resource))) return zip(*sorted(resource.items()))
else: else:
return None return None

View File

@ -14,9 +14,6 @@
# under the License. # under the License.
# #
import six
from neutronclient._i18n import _ from neutronclient._i18n import _
from neutronclient.neutron import v2_0 as neutronV20 from neutronclient.neutron import v2_0 as neutronV20
@ -119,6 +116,6 @@ class RetrievePoolStats(neutronV20.ShowCommand):
self.format_output_data(data) self.format_output_data(data)
stats = data['stats'] stats = data['stats']
if 'stats' in data: if 'stats' in data:
return zip(*sorted(six.iteritems(stats))) return zip(*sorted(stats.items()))
else: else:
return None return None

View File

@ -12,7 +12,6 @@
# #
from cliff import show from cliff import show
import six
from neutronclient._i18n import _ from neutronclient._i18n import _
from neutronclient.neutron import v2_0 as neutronV20 from neutronclient.neutron import v2_0 as neutronV20
@ -68,6 +67,6 @@ class ShowIpAvailability(neutronV20.NeutronCommand, show.ShowOne):
self.format_output_data(data) self.format_output_data(data)
resource = data[self.resource] resource = data[self.resource]
if self.resource in data: if self.resource in data:
return zip(*sorted(six.iteritems(resource))) return zip(*sorted(resource.items()))
else: else:
return None return None

View File

@ -22,7 +22,6 @@ import argparse
from cliff import lister from cliff import lister
from cliff import show from cliff import show
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
import six
from neutronclient._i18n import _ from neutronclient._i18n import _
from neutronclient.common import exceptions from neutronclient.common import exceptions
@ -121,7 +120,7 @@ class ShowQuotaBase(neutronV20.NeutronCommand, show.ShowOne):
tenant_id = get_tenant_id(parsed_args, neutron_client) tenant_id = get_tenant_id(parsed_args, neutron_client)
data = self.retrieve_data(tenant_id, neutron_client) data = self.retrieve_data(tenant_id, neutron_client)
if self.resource in data: if self.resource in data:
return zip(*sorted(six.iteritems(data[self.resource]))) return zip(*sorted(data[self.resource].items()))
return return
@ -241,7 +240,7 @@ class UpdateQuota(neutronV20.NeutronCommand, show.ShowOne):
tenant_id = get_tenant_id(parsed_args, neutron_client) tenant_id = get_tenant_id(parsed_args, neutron_client)
data = obj_updator(tenant_id, body) data = obj_updator(tenant_id, body)
if self.resource in data: if self.resource in data:
for k, v in six.iteritems(data[self.resource]): for k, v in data[self.resource].items():
if isinstance(v, list): if isinstance(v, list):
value = "" value = ""
for _item in v: for _item in v:
@ -254,6 +253,6 @@ class UpdateQuota(neutronV20.NeutronCommand, show.ShowOne):
data[self.resource][k] = value data[self.resource][k] = value
elif v is None: elif v is None:
data[self.resource][k] = '' data[self.resource][k] = ''
return zip(*sorted(six.iteritems(data[self.resource]))) return zip(*sorted(data[self.resource].items()))
else: else:
return return

View File

@ -14,7 +14,6 @@
# under the License. # under the License.
# #
import six
import testtools import testtools
from neutronclient.common import exceptions from neutronclient.common import exceptions
@ -116,7 +115,7 @@ class CLITestArgs(testtools.TestCase):
neutronV20.parse_args_to_dict, _specs) neutronV20.parse_args_to_dict, _specs)
self.assertEqual('Invalid value_specs --badtypearg type=badtype val1: ' self.assertEqual('Invalid value_specs --badtypearg type=badtype val1: '
'type badtype is not supported', 'type badtype is not supported',
six.text_type(ex)) str(ex))
def test_clear_action(self): def test_clear_action(self):
_specs = ['--anyarg', 'action=clear'] _specs = ['--anyarg', 'action=clear']
@ -128,7 +127,7 @@ class CLITestArgs(testtools.TestCase):
ex = self.assertRaises(exceptions.CommandError, ex = self.assertRaises(exceptions.CommandError,
neutronV20.parse_args_to_dict, _specs) neutronV20.parse_args_to_dict, _specs)
self.assertEqual('Invalid values_specs --strarg type=str', self.assertEqual('Invalid values_specs --strarg type=str',
six.text_type(ex)) str(ex))
def test_bad_values_list(self): def test_bad_values_list(self):
_specs = ['--listarg', 'list=true', 'type=str'] _specs = ['--listarg', 'list=true', 'type=str']

View File

@ -15,16 +15,16 @@
# #
import contextlib import contextlib
from io import StringIO
import itertools import itertools
import sys import sys
import urllib.parse as urlparse
import mock import mock
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
from oslo_utils import encodeutils from oslo_utils import encodeutils
from oslotest import base from oslotest import base
import requests import requests
import six
import six.moves.urllib.parse as urlparse
import yaml import yaml
from neutronclient.common import constants from neutronclient.common import constants
@ -43,7 +43,7 @@ REQUEST_ID = 'test_request_id'
@contextlib.contextmanager @contextlib.contextmanager
def capture_std_streams(): def capture_std_streams():
fake_stdout, fake_stderr = six.StringIO(), six.StringIO() fake_stdout, fake_stderr = StringIO(), StringIO()
stdout, stderr = sys.stdout, sys.stderr stdout, stderr = sys.stdout, sys.stderr
try: try:
sys.stdout, sys.stderr = fake_stdout, fake_stderr sys.stdout, sys.stderr = fake_stdout, fake_stderr
@ -125,7 +125,7 @@ class MyComparator(object):
def _com_dict(self, lhs, rhs): def _com_dict(self, lhs, rhs):
if len(lhs) != len(rhs): if len(lhs) != len(rhs):
return False return False
for key, value in six.iteritems(lhs): for key, value in lhs.items():
if key not in rhs: if key not in rhs:
return False return False
rhs_value = rhs[key] rhs_value = rhs[key]
@ -743,7 +743,7 @@ class ClientV2TestJson(CLITestV20Base):
def test_do_request_error_without_response_body(self): def test_do_request_error_without_response_body(self):
params = {'test': 'value'} params = {'test': 'value'}
expect_query = six.moves.urllib.parse.urlencode(params) expect_query = urlparse.urlencode(params)
self.client.httpclient.auth_token = 'token' self.client.httpclient.auth_token = 'token'
resp_headers = {'x-openstack-request-id': REQUEST_ID} resp_headers = {'x-openstack-request-id': REQUEST_ID}
resp = (MyResp(400, headers=resp_headers, reason='An error'), '') resp = (MyResp(400, headers=resp_headers, reason='An error'), '')
@ -772,7 +772,7 @@ class ClientV2TestJson(CLITestV20Base):
def test_do_request_request_ids(self): def test_do_request_request_ids(self):
params = {'test': 'value'} params = {'test': 'value'}
expect_query = six.moves.urllib.parse.urlencode(params) expect_query = urlparse.urlencode(params)
self.client.httpclient.auth_token = 'token' self.client.httpclient.auth_token = 'token'
body = params body = params
expect_body = self.client.serialize(body) expect_body = self.client.serialize(body)
@ -866,7 +866,7 @@ class ClientV2TestJson(CLITestV20Base):
def test_update_resource(self): def test_update_resource(self):
params = {'test': 'value'} params = {'test': 'value'}
expect_query = six.moves.urllib.parse.urlencode(params) expect_query = urlparse.urlencode(params)
self.client.httpclient.auth_token = 'token' self.client.httpclient.auth_token = 'token'
body = params body = params
expect_body = self.client.serialize(body) expect_body = self.client.serialize(body)
@ -889,7 +889,7 @@ class ClientV2TestJson(CLITestV20Base):
def test_update_resource_with_revision_number(self): def test_update_resource_with_revision_number(self):
params = {'test': 'value'} params = {'test': 'value'}
expect_query = six.moves.urllib.parse.urlencode(params) expect_query = urlparse.urlencode(params)
self.client.httpclient.auth_token = 'token' self.client.httpclient.auth_token = 'token'
body = params body = params
expect_body = self.client.serialize(body) expect_body = self.client.serialize(body)

View File

@ -15,10 +15,10 @@
# under the License. # under the License.
import sys import sys
import urllib.parse as urlparse
import mock import mock
from oslo_utils import uuidutils from oslo_utils import uuidutils
import six
from neutronclient.common import exceptions from neutronclient.common import exceptions
from neutronclient.common import utils from neutronclient.common import utils
@ -250,7 +250,7 @@ class CLITestV20SecurityGroupsJSON(test_cli20.CLITestV20Base):
resp_str = self.client.serialize({'security_groups': response}) resp_str = self.client.serialize({'security_groups': response})
result.append({ result.append({
'filter': six.moves.urllib.parse.urlencode(params, doseq=1), 'filter': urlparse.urlencode(params, doseq=1),
'response': (test_cli20.MyResp(200), resp_str), 'response': (test_cli20.MyResp(200), resp_str),
}) })

View File

@ -16,7 +16,6 @@ import sys
import mock import mock
from oslo_utils import encodeutils from oslo_utils import encodeutils
import six
import testtools import testtools
from neutronclient._i18n import _ from neutronclient._i18n import _
@ -46,4 +45,4 @@ class TestExceptions(testtools.TestCase):
multibyte_binary = encodeutils.safe_encode(multibyte_string) multibyte_binary = encodeutils.safe_encode(multibyte_string)
e = TestException(reason=multibyte_binary) e = TestException(reason=multibyte_binary)
self.assertEqual('Exception with %s' % multibyte_string, self.assertEqual('Exception with %s' % multibyte_string,
six.text_type(e)) str(e))

View File

@ -19,7 +19,6 @@ from oslo_utils import uuidutils
import osprofiler.profiler import osprofiler.profiler
import osprofiler.web import osprofiler.web
from requests_mock.contrib import fixture as mock_fixture from requests_mock.contrib import fixture as mock_fixture
import six
import testtools import testtools
from neutronclient import client from neutronclient import client
@ -33,8 +32,7 @@ URL = 'http://test.test:1234/v2.0/test'
BODY = 'IAMFAKE' BODY = 'IAMFAKE'
@six.add_metaclass(abc.ABCMeta) class TestHTTPClientMixin(object, metaclass=abc.ABCMeta):
class TestHTTPClientMixin(object):
def setUp(self): def setUp(self):
super(TestHTTPClientMixin, self).setUp() super(TestHTTPClientMixin, self).setUp()

View File

@ -14,6 +14,7 @@
# under the License. # under the License.
import argparse import argparse
from io import StringIO
import logging import logging
import os import os
import re import re
@ -22,7 +23,6 @@ import sys
import fixtures import fixtures
from keystoneauth1 import session from keystoneauth1 import session
import mock import mock
import six
import testtools import testtools
from testtools import matchers from testtools import matchers
@ -75,8 +75,8 @@ class ShellTest(testtools.TestCase):
clean_env = {} clean_env = {}
_old_env, os.environ = os.environ, clean_env.copy() _old_env, os.environ = os.environ, clean_env.copy()
try: try:
sys.stdout = six.moves.cStringIO() sys.stdout = StringIO()
sys.stderr = six.moves.cStringIO() sys.stderr = StringIO()
_shell = openstack_shell.NeutronShell('2.0') _shell = openstack_shell.NeutronShell('2.0')
_shell.run(argstr.split()) _shell.run(argstr.split())
except SystemExit: except SystemExit:

View File

@ -21,12 +21,11 @@ import itertools
import logging import logging
import re import re
import time import time
import urllib.parse as urlparse
import debtcollector.renames import debtcollector.renames
from keystoneauth1 import exceptions as ksa_exc from keystoneauth1 import exceptions as ksa_exc
import requests import requests
import six.moves.urllib.parse as urlparse
from six import string_types
from neutronclient._i18n import _ from neutronclient._i18n import _
from neutronclient import client from neutronclient import client
@ -398,7 +397,7 @@ class ClientBase(object):
if item: if item:
if isinstance(item, dict): if isinstance(item, dict):
return _DictWithMeta(item, resp) return _DictWithMeta(item, resp)
elif isinstance(item, string_types): elif isinstance(item, str):
return _StrWithMeta(item, resp) return _StrWithMeta(item, resp)
else: else:
return _TupleWithMeta((), resp) return _TupleWithMeta((), resp)

View File

@ -18,4 +18,3 @@ keystoneauth1>=3.4.0 # Apache-2.0
python-keystoneclient>=3.8.0 # Apache-2.0 python-keystoneclient>=3.8.0 # Apache-2.0
requests>=2.14.2 # Apache-2.0 requests>=2.14.2 # Apache-2.0
simplejson>=3.5.1 # MIT simplejson>=3.5.1 # MIT
six>=1.10.0 # MIT