Replace six.iteritems() with .items()

1.As mentioned in [1], we should avoid usingg
six.iteritems to achieve iterators. We can
use dict.items instead, as it will return
iterators in PY3 as well. And dict.items/keys
will more readable. 2.In py2, the performance
about list should be negligible, see the link [2].
[1] https://wiki.openstack.org/wiki/Python3
[2] http://lists.openstack.org/pipermail/openstack-dev/2015-June/066391.html

Change-Id: I71c13040318eca6e5ed993e8aa03f8003986a71c
This commit is contained in:
ji-xuepeng 2017-02-08 16:27:54 +08:00
parent c1f54742f9
commit 5fca39dbde
11 changed files with 22 additions and 25 deletions

View File

@ -53,7 +53,7 @@ def encode_headers(headers):
names and values
"""
return dict((encodeutils.safe_encode(h), encodeutils.safe_encode(v))
for h, v in six.iteritems(headers) if v is not None)
for h, v in headers.items() if v is not None)
class _BaseHTTPClient(object):
@ -181,7 +181,7 @@ class HTTPClient(_BaseHTTPClient):
headers = copy.deepcopy(headers)
headers.update(self.session.headers)
for (key, value) in six.iteritems(headers):
for (key, value) in headers.items():
header = '-H \'%s: %s\'' % utils.safe_header(key, value)
curl.append(header)
@ -227,7 +227,7 @@ class HTTPClient(_BaseHTTPClient):
headers = copy.deepcopy(kwargs.pop('headers', {}))
if self.identity_headers:
for k, v in six.iteritems(self.identity_headers):
for k, v in self.identity_headers.items():
headers.setdefault(k, v)
data = self._set_common_request_kwargs(headers, kwargs)

View File

@ -122,7 +122,7 @@ def schema_args(schema_getter, omit=None):
kwargs))
else:
properties = schema.get('properties', {})
for name, property in six.iteritems(properties):
for name, property in properties.items():
if name in omit:
continue
param = '--' + name.replace('_', '-')
@ -186,7 +186,7 @@ def print_list(objs, fields, formatters=None, field_settings=None):
row = []
for field in fields:
if field in field_settings:
for setting, value in six.iteritems(field_settings[field]):
for setting, value in field_settings[field].items():
setting_dict = getattr(pt, setting)
setting_dict[field] = value
@ -205,7 +205,7 @@ def print_dict(d, max_column_width=80):
pt = prettytable.PrettyTable(['Property', 'Value'], caching=False)
pt.align = 'l'
pt.max_width = max_column_width
for k, v in six.iteritems(d):
for k, v in d.items():
if isinstance(v, (dict, list)):
v = json.dumps(v)
pt.add_row([k, v])
@ -388,7 +388,7 @@ def strip_version(endpoint):
def print_image(image_obj, human_readable=False, max_col_width=None):
ignore = ['self', 'access', 'file', 'schema']
image = dict([item for item in six.iteritems(image_obj)
image = dict([item for item in image_obj.items()
if item[0] not in ignore])
if human_readable:
image['size'] = make_size_human_readable(image['size'])

View File

@ -134,7 +134,7 @@ class TestClient(testtools.TestCase):
http_client.get(path)
headers = self.mock.last_request.headers
for k, v in six.iteritems(identity_headers):
for k, v in identity_headers.items():
self.assertEqual(v, headers[k])
def test_language_header_passed(self):
@ -326,7 +326,7 @@ class TestClient(testtools.TestCase):
'LOG.debug called with no arguments')
needles = {'key': key, 'cert': cert, 'cacert': cacert}
for option, value in six.iteritems(needles):
for option, value in needles.items():
if value:
regex = ".*\s--%s\s+('%s'|%s).*" % (option, value, value)
self.assertThat(mock_log.call_args[0][0],

View File

@ -13,7 +13,6 @@
# License for the specific language governing permissions and limitations
# under the License.
import six
import testtools
from glanceclient.tests.unit.v2 import base
@ -276,7 +275,7 @@ class TestObjectController(testtools.TestCase):
obj = self.controller.get(NAMESPACE1, OBJECT1)
self.assertEqual(OBJECT1, obj.name)
self.assertEqual(sorted([PROPERTY1, PROPERTY2]),
sorted(list(six.iterkeys(obj.properties))))
sorted(list(obj.properties.keys())))
def test_create_object(self):
properties = {

View File

@ -317,7 +317,7 @@ class CrudManager(BaseManager):
def _filter_kwargs(self, kwargs):
"""Drop null values and handle ids."""
for key, ref in six.iteritems(kwargs.copy()):
for key, ref in kwargs.copy().items():
if ref is None:
kwargs.pop(key)
else:
@ -475,7 +475,7 @@ class Resource(object):
return None
def _add_details(self, info):
for (k, v) in six.iteritems(info):
for (k, v) in info.items():
try:
setattr(self, k, v)
self._info[k] = v

View File

@ -421,7 +421,7 @@ class HttpVersionNotSupported(HttpServerError):
# _code_map contains all the classes that have http_status attribute.
_code_map = dict(
(getattr(obj, 'http_status', None), obj)
for name, obj in six.iteritems(vars(sys.modules[__name__]))
for name, obj in vars(sys.modules[__name__]).items()
if inspect.isclass(obj) and getattr(obj, 'http_status', False)
)

View File

@ -72,7 +72,7 @@ class ImageManager(base.ManagerWithFind):
def _image_meta_from_headers(self, headers):
meta = {'properties': {}}
safe_decode = encodeutils.safe_decode
for key, value in six.iteritems(headers):
for key, value in headers.items():
# NOTE(flaper87): this is a compatibility fix
# for urllib3 >= 1.11. Please, refer to this
# bug for more info:
@ -105,9 +105,9 @@ class ImageManager(base.ManagerWithFind):
return str(value)
return value
for key, value in six.iteritems(fields_copy.pop('properties', {})):
for key, value in fields_copy.pop('properties', {}).items():
headers['x-image-meta-property-%s' % key] = to_str(value)
for key, value in six.iteritems(fields_copy):
for key, value in fields_copy.items():
headers['x-image-meta-%s' % key] = to_str(value)
return headers
@ -224,7 +224,7 @@ class ImageManager(base.ManagerWithFind):
return not (image.owner == owner)
def paginate(qp, return_request_id=None):
for param, value in six.iteritems(qp):
for param, value in qp.items():
if isinstance(value, six.string_types):
# Note(flaper87) Url encoding should
# be moved inside http utils, at least

View File

@ -18,7 +18,6 @@ from __future__ import print_function
import copy
import functools
import os
import six
import sys
from oslo_utils import encodeutils
@ -128,7 +127,7 @@ def _image_show(image, human_readable=False, max_column_width=80):
info = copy.deepcopy(image._info)
if human_readable:
info['size'] = utils.make_size_human_readable(info['size'])
for (k, v) in six.iteritems(info.pop('properties')):
for (k, v) in info.pop('properties').items():
info['Property \'%s\'' % k] = v
utils.print_dict(info, max_column_width=max_column_width)

View File

@ -146,7 +146,7 @@ class Controller(object):
tags_url_params.append({'tag': encodeutils.safe_encode(tag)})
for param, value in six.iteritems(filters):
for param, value in filters.items():
if isinstance(value, six.string_types):
filters[param] = encodeutils.safe_encode(value)

View File

@ -60,7 +60,7 @@ class NamespaceController(object):
:param kwargs: Unpacked namespace object.
"""
namespace = self.get(namespace_name)
for (key, value) in six.iteritems(kwargs):
for (key, value) in kwargs.items():
try:
setattr(namespace, key, value)
except warlock.InvalidOperation as e:
@ -174,7 +174,7 @@ class NamespaceController(object):
raise ValueError('sort_dir must be one of the following: %s.'
% ', '.join(SORT_DIR_VALUES))
for param, value in six.iteritems(filters):
for param, value in filters.items():
if isinstance(value, list):
filters[param] = encodeutils.safe_encode(','.join(value))
elif isinstance(value, six.string_types):

View File

@ -16,7 +16,6 @@
import copy
import json
import jsonpatch
import six
import warlock.model as warlock
@ -51,7 +50,7 @@ class SchemaBasedModel(warlock.Model):
original = copy.deepcopy(self.__dict__['__original__'])
new = dict(self)
if self.schema:
for (name, prop) in six.iteritems(self.schema['properties']):
for (name, prop) in self.schema['properties'].items():
if (name not in original and name in new and
prop.get('is_base', True)):
original[name] = None