Replace six.iteritems() with .items()

1.As mentioned in [1], we should avoid using 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: I18a6890935ebdbb589269379f21a0dd47d07eb3a
This commit is contained in:
M V P Nitesh
2017-04-03 18:20:15 +05:30
parent cfd3373086
commit 46b9e429a2
18 changed files with 24 additions and 35 deletions

View File

@@ -52,14 +52,14 @@ def getid(obj):
def filter_none(**kwargs): def filter_none(**kwargs):
"""Remove any entries from a dictionary where the value is None.""" """Remove any entries from a dictionary where the value is None."""
return dict((k, v) for k, v in six.iteritems(kwargs) if v is not None) return dict((k, v) for k, v in kwargs.items() if v is not None)
def filter_kwargs(f): def filter_kwargs(f):
@functools.wraps(f) @functools.wraps(f)
def func(*args, **kwargs): def func(*args, **kwargs):
new_kwargs = {} new_kwargs = {}
for key, ref in six.iteritems(kwargs): for key, ref in kwargs.items():
if ref is None: if ref is None:
# drop null values # drop null values
continue continue
@@ -481,7 +481,7 @@ class Resource(object):
return None return None
def _add_details(self, info): def _add_details(self, info):
for (k, v) in six.iteritems(info): for (k, v) in info.items():
try: try:
try: try:
setattr(self, k, v) setattr(self, k, v)

View File

@@ -218,7 +218,7 @@ class Ec2Signer(object):
# - the Authorization header (SignedHeaders key) # - the Authorization header (SignedHeaders key)
# - the X-Amz-SignedHeaders query parameter # - the X-Amz-SignedHeaders query parameter
headers_lower = dict((k.lower().strip(), v.strip()) headers_lower = dict((k.lower().strip(), v.strip())
for (k, v) in six.iteritems(headers)) for (k, v) in headers.items())
# Boto versions < 2.9.3 strip the port component of the host:port # Boto versions < 2.9.3 strip the port component of the host:port
# header, so detect the user-agent via the header and strip the # header, so detect the user-agent via the header and strip the

View File

@@ -16,7 +16,6 @@ import warnings
from debtcollector import removals from debtcollector import removals
from keystoneauth1 import plugin from keystoneauth1 import plugin
from positional import positional from positional import positional
import six
from keystoneclient import _discover from keystoneclient import _discover
from keystoneclient import exceptions from keystoneclient import exceptions
@@ -300,7 +299,7 @@ class Discover(_discover.Discover):
raise exceptions.DiscoveryFailure(msg) raise exceptions.DiscoveryFailure(msg)
# kwargs should take priority over stored kwargs. # kwargs should take priority over stored kwargs.
for k, v in six.iteritems(self._client_kwargs): for k, v in self._client_kwargs.items():
kwargs.setdefault(k, v) kwargs.setdefault(k, v)
# restore the url to either auth_url or endpoint depending on what # restore the url to either auth_url or endpoint depending on what

View File

@@ -201,7 +201,7 @@ class Session(object):
string_parts.append(url) string_parts.append(url)
if headers: if headers:
for header in six.iteritems(headers): for header in headers.items():
string_parts.append('-H "%s: %s"' string_parts.append('-H "%s: %s"'
% self._process_header(header)) % self._process_header(header))
@@ -249,7 +249,7 @@ class Session(object):
'RESP:', 'RESP:',
'[%s]' % response.status_code '[%s]' % response.status_code
] ]
for header in six.iteritems(response.headers): for header in response.headers.items():
string_parts.append('%s: %s' % self._process_header(header)) string_parts.append('%s: %s' % self._process_header(header))
string_parts.append('\nRESP BODY: %s\n' % strutils.mask_password(text)) string_parts.append('\nRESP BODY: %s\n' % strutils.mask_password(text))

View File

@@ -13,8 +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
from keystoneclient import exceptions from keystoneclient import exceptions
from keystoneclient.tests.unit import utils from keystoneclient.tests.unit import utils
@@ -23,7 +21,7 @@ class FakeResponse(object):
json_data = {} json_data = {}
def __init__(self, **kwargs): def __init__(self, **kwargs):
for key, value in six.iteritems(kwargs): for key, value in kwargs.items():
setattr(self, key, value) setattr(self, key, value)
def json(self): def json(self):

View File

@@ -461,7 +461,7 @@ class GenericAuthPluginTests(utils.TestCase):
self.assertEqual(text, resp.text) self.assertEqual(text, resp.text)
for k, v in six.iteritems(self.auth.headers): for k, v in self.auth.headers.items():
self.assertRequestHeaderEqual(k, v) self.assertRequestHeaderEqual(k, v)
with self.deprecations.expect_deprecations_here(): with self.deprecations.expect_deprecations_here():

View File

@@ -12,7 +12,6 @@
import uuid import uuid
import six
from keystoneclient.tests.unit.auth import utils from keystoneclient.tests.unit.auth import utils
@@ -39,7 +38,7 @@ class TestOtherLoading(utils.TestCase):
self.assertEqual(set(vals), set(called_opts)) self.assertEqual(set(vals), set(called_opts))
for k, v in six.iteritems(vals): for k, v in vals.items():
# replace - to _ because it's the dest used to create kwargs # replace - to _ because it's the dest used to create kwargs
self.assertEqual(v, p[k.replace('-', '_')]) self.assertEqual(v, p[k.replace('-', '_')])

View File

@@ -16,7 +16,6 @@ import uuid
from keystoneauth1 import fixture from keystoneauth1 import fixture
import mock import mock
from oslo_config import cfg from oslo_config import cfg
import six
from keystoneclient import access from keystoneclient import access
from keystoneclient.auth import base from keystoneclient.auth import base
@@ -88,7 +87,7 @@ class TestCase(utils.TestCase):
'a_bool': a_bool} 'a_bool': a_bool}
def assertTestVals(self, plugin, vals=TEST_VALS): def assertTestVals(self, plugin, vals=TEST_VALS):
for k, v in six.iteritems(vals): for k, v in vals.items():
self.assertEqual(v, plugin[k]) self.assertEqual(v, plugin[k])

View File

@@ -703,7 +703,7 @@ class Examples(fixtures.Fixture):
self.TOKEN_RESPONSES[self.SIGNED_v3_TOKEN_SCOPED_KEY]) self.TOKEN_RESPONSES[self.SIGNED_v3_TOKEN_SCOPED_KEY])
self.JSON_TOKEN_RESPONSES = dict([(k, jsonutils.dumps(v)) for k, v in self.JSON_TOKEN_RESPONSES = dict([(k, jsonutils.dumps(v)) for k, v in
six.iteritems(self.TOKEN_RESPONSES)]) self.TOKEN_RESPONSES.items()])
EXAMPLES_RESOURCE = testresources.FixtureResource(Examples()) EXAMPLES_RESOURCE = testresources.FixtureResource(Examples())

View File

@@ -243,7 +243,7 @@ class AvailableVersionsTests(utils.TestCase):
'cinder': jsonutils.dumps(CINDER_EXAMPLES), 'cinder': jsonutils.dumps(CINDER_EXAMPLES),
'glance': jsonutils.dumps(GLANCE_EXAMPLES)} 'glance': jsonutils.dumps(GLANCE_EXAMPLES)}
for path, text in six.iteritems(examples): for path, text in examples.items():
url = "%s%s" % (BASE_URL, path) url = "%s%s" % (BASE_URL, path)
self.requests_mock.get(url, status_code=300, text=text) self.requests_mock.get(url, status_code=300, text=text)

View File

@@ -12,7 +12,6 @@
import uuid import uuid
import six
from keystoneclient import fixture from keystoneclient import fixture
from keystoneclient.tests.unit import utils from keystoneclient.tests.unit import utils
@@ -246,7 +245,7 @@ class V3TokenTests(utils.TestCase):
# the endpoint content below easier. # the endpoint content below easier.
self.assertTrue(endpoint.pop('id')) self.assertTrue(endpoint.pop('id'))
for interface, url in six.iteritems(endpoints): for interface, url in endpoints.items():
endpoint = {'interface': interface, 'url': url, endpoint = {'interface': interface, 'url': url,
'region': region, 'region_id': region} 'region': region, 'region_id': region}
self.assertIn(endpoint, service['endpoints']) self.assertIn(endpoint, service['endpoints'])

View File

@@ -202,10 +202,10 @@ class BasicRequestTests(utils.TestCase):
self.request(headers=headers) self.request(headers=headers)
for k, v in six.iteritems(headers): for k, v in headers.items():
self.assertRequestHeaderEqual(k, v) self.assertRequestHeaderEqual(k, v)
for header in six.iteritems(headers): for header in headers.items():
self.assertThat(self.logger_message.getvalue(), self.assertThat(self.logger_message.getvalue(),
matchers.Contains('-H "%s: %s"' % header)) matchers.Contains('-H "%s: %s"' % header))

View File

@@ -171,13 +171,13 @@ class SessionTests(utils.TestCase):
self.assertIn(body, self.logger.output) self.assertIn(body, self.logger.output)
self.assertIn("'%s'" % data, self.logger.output) self.assertIn("'%s'" % data, self.logger.output)
for k, v in six.iteritems(headers): for k, v in headers.items():
self.assertIn(k, self.logger.output) self.assertIn(k, self.logger.output)
self.assertIn(v, self.logger.output) self.assertIn(v, self.logger.output)
# Assert that response headers contains actual values and # Assert that response headers contains actual values and
# only debug logs has been masked # only debug logs has been masked
for k, v in six.iteritems(security_headers): for k, v in security_headers.items():
self.assertIn('%s: {SHA1}' % k, self.logger.output) self.assertIn('%s: {SHA1}' % k, self.logger.output)
self.assertEqual(v, resp.headers[k]) self.assertEqual(v, resp.headers[k])
self.assertNotIn(v, self.logger.output) self.assertNotIn(v, self.logger.output)

View File

@@ -19,7 +19,6 @@ from oslo_serialization import jsonutils
import requests import requests
import requests_mock import requests_mock
from requests_mock.contrib import fixture from requests_mock.contrib import fixture
import six
from six.moves.urllib import parse as urlparse from six.moves.urllib import parse as urlparse
import testscenarios import testscenarios
import testtools import testtools
@@ -97,7 +96,7 @@ class TestCase(testtools.TestCase):
parts = urlparse.urlparse(self.requests_mock.last_request.url) parts = urlparse.urlparse(self.requests_mock.last_request.url)
qs = urlparse.parse_qs(parts.query, keep_blank_values=True) qs = urlparse.parse_qs(parts.query, keep_blank_values=True)
for k, v in six.iteritems(kwargs): for k, v in kwargs.items():
self.assertIn(k, qs) self.assertIn(k, qs)
self.assertIn(v, qs[k]) self.assertIn(v, qs[k])

View File

@@ -14,7 +14,6 @@ import json
import uuid import uuid
from keystoneauth1 import fixture from keystoneauth1 import fixture
import six
from keystoneauth1 import session as auth_session from keystoneauth1 import session as auth_session
from keystoneclient.auth import token_endpoint from keystoneclient.auth import token_endpoint
@@ -207,7 +206,7 @@ class KeystoneClientTest(utils.TestCase):
cl = client.Client(session=sess, **opts) cl = client.Client(session=sess, **opts)
for k, v in six.iteritems(opts): for k, v in opts.items():
self.assertEqual(v, getattr(cl._adapter, k)) self.assertEqual(v, getattr(cl._adapter, k))
self.assertEqual('identity', cl._adapter.service_type) self.assertEqual('identity', cl._adapter.service_type)

View File

@@ -14,7 +14,6 @@ import copy
import json import json
import uuid import uuid
import six
from keystoneauth1 import session as auth_session from keystoneauth1 import session as auth_session
from keystoneclient.auth import token_endpoint from keystoneclient.auth import token_endpoint
@@ -257,7 +256,7 @@ class KeystoneClientTest(utils.TestCase):
cl = client.Client(session=sess, **opts) cl = client.Client(session=sess, **opts)
for k, v in six.iteritems(opts): for k, v in opts.items():
self.assertEqual(v, getattr(cl._adapter, k)) self.assertEqual(v, getattr(cl._adapter, k))
self.assertEqual('identity', cl._adapter.service_type) self.assertEqual('identity', cl._adapter.service_type)

View File

@@ -12,7 +12,6 @@
import uuid import uuid
import six
from six.moves.urllib import parse as urlparse from six.moves.urllib import parse as urlparse
from keystoneclient.tests.unit import client_fixtures from keystoneclient.tests.unit import client_fixtures
@@ -301,7 +300,7 @@ class CrudTests(object):
qs_args = self.requests_mock.last_request.qs qs_args = self.requests_mock.last_request.qs
qs_args_expected = expected_query or filter_kwargs qs_args_expected = expected_query or filter_kwargs
for key, value in six.iteritems(qs_args_expected): for key, value in qs_args_expected.items():
self.assertIn(key, qs_args) self.assertIn(key, qs_args)
# The querystring value is a list. Note we convert the value to a # The querystring value is a list. Note we convert the value to a
# string and lower, as the query string is always a string and the # string and lower, as the query string is always a string and the

View File

@@ -15,7 +15,6 @@
# under the License. # under the License.
from keystoneauth1 import plugin from keystoneauth1 import plugin
import six
from six.moves import urllib from six.moves import urllib
from keystoneclient import base from keystoneclient import base
@@ -92,7 +91,7 @@ class TenantManager(base.ManagerWithFind):
"enabled": enabled}} "enabled": enabled}}
# Allow Extras Passthru and ensure we don't clobber primary arguments. # Allow Extras Passthru and ensure we don't clobber primary arguments.
for k, v in six.iteritems(kwargs): for k, v in kwargs.items():
if k not in params['tenant']: if k not in params['tenant']:
params['tenant'][k] = v params['tenant'][k] = v
@@ -142,7 +141,7 @@ class TenantManager(base.ManagerWithFind):
body['tenant']['description'] = description body['tenant']['description'] = description
# Allow Extras Passthru and ensure we don't clobber primary arguments. # Allow Extras Passthru and ensure we don't clobber primary arguments.
for k, v in six.iteritems(kwargs): for k, v in kwargs.items():
if k not in body['tenant']: if k not in body['tenant']:
body['tenant'][k] = v body['tenant'][k] = v