Use dict comprehensions instead of dict constructor

PEP-0274 introduced dict comprehensions to replace dict constructor
with a sequence of key-value pair, these are benefits copied
from [1]:
  The dictionary constructor approach has two distinct disadvantages
  from the proposed syntax though.  First, it isn't as legible as a
  dict comprehension.  Second, it forces the programmer to create an
  in-core list object first, which could be expensive.
There is deep dive about PEP-0274[2] and basic tests about
performance[3].
Note: This commit doesn't handle dict constructor with kwagrs.

[1]http://legacy.python.org/dev/peps/pep-0274/
[2]http://doughellmann.com/2012/11/12/the-performance-impact-of-using-dict-instead-of-in-cpython-2-7-2.html
[3]http://paste.openstack.org/show/154798/

Change-Id: I45d0c289ecaf63a343fc9ad935cf2893d67d938a
This commit is contained in:
ChangBo Guo(gcb) 2014-12-24 23:05:48 +08:00
parent f86a0e6cc2
commit 0ee91a5854
8 changed files with 17 additions and 20 deletions

View File

@ -23,7 +23,7 @@ class UnprocessableEntity(exceptions.ClientException):
message = "Unprocessable Entity"
_code_map = dict((c.http_status, c) for c in [UnprocessableEntity])
_code_map = {c.http_status: c for c in [UnprocessableEntity]}
def from_response(response, body):

View File

@ -56,7 +56,7 @@ class Limit(object):
60 * 60 * 24: "DAY",
}
UNIT_MAP = dict([(v, k) for k, v in UNITS.items()])
UNIT_MAP = {v: k for k, v in UNITS.items()}
def __init__(self, verb, uri, regex, value, unit):
"""

View File

@ -42,7 +42,7 @@ class ModelBase(object):
def data(self, **options):
"""Called to serialize object to a dictionary."""
data_fields = self._data_fields + self._auto_generated_attrs
return dict([(field, self[field]) for field in data_fields])
return {field: self[field] for field in data_fields}
def is_valid(self):
"""Called when persisting data to ensure the format is correct."""
@ -84,8 +84,7 @@ class RemoteModelBase(ModelBase):
def _data_item(self, data_object):
data_fields = self._data_fields + self._auto_generated_attrs
return dict([(field, getattr(data_object, field))
for field in data_fields])
return {field: getattr(data_object, field) for field in data_fields}
# data magic that will allow for a list of _data_object or a single item
# if the object is a list, it will turn it into a list of hash's again

View File

@ -69,14 +69,14 @@ def create_method_args_string(*args, **kwargs):
def stringify_keys(dictionary):
if dictionary is None:
return None
return dict((str(key), value) for key, value in dictionary.iteritems())
return {str(key): value for key, value in dictionary.iteritems()}
def exclude(key_values, *exclude_keys):
if key_values is None:
return None
return dict((key, value) for key, value in key_values.iteritems()
if key not in exclude_keys)
return {key: value for key, value in key_values.iteritems()
if key not in exclude_keys}
def generate_uuid():

View File

@ -409,8 +409,8 @@ class Controller(object):
self.exception_map)
def _extract_limits(self, params):
return dict([(key, params[key]) for key in params.keys()
if key in ["limit", "marker"]])
return {key: params[key] for key in params.keys()
if key in ["limit", "marker"]}
class TroveResponseSerializer(base_wsgi.ResponseSerializer):
@ -513,8 +513,8 @@ class ContextMiddleware(base_wsgi.Middleware):
super(ContextMiddleware, self).__init__(application)
def _extract_limits(self, params):
return dict([(key, params[key]) for key in params.keys()
if key in ["limit", "marker"]])
return {key: params[key] for key in params.keys()
if key in ["limit", "marker"]}
def process_request(self, request):
service_catalog = None

View File

@ -39,7 +39,7 @@ class SecurityGroupController(wsgi.Controller):
deleted=False)
# Construct the mapping from Security Groups to Security Group Rules
rules_map = dict([(g.id, g.get_rules()) for g in sec_groups])
rules_map = {g.id: g.get_rules() for g in sec_groups}
return wsgi.Result(
views.SecurityGroupsView(sec_groups,

View File

@ -28,7 +28,7 @@ class LimitsController(wsgi.Controller):
Return all absolute and rate limit information.
"""
quotas = QUOTAS.get_all_quotas_by_tenant(tenant_id)
abs_limits = dict((k, v['hard_limit']) for k, v in quotas.items())
abs_limits = {k: v['hard_limit'] for k, v in quotas.items()}
rate_limits = req.environ.get("trove.limits", [])
return wsgi.Result(views.LimitViews(abs_limits,

View File

@ -58,9 +58,8 @@ class DbQuotaDriver(object):
"""
all_quotas = Quota.find_all(tenant_id=tenant_id).all()
result_quotas = dict((quota.resource, quota)
for quota in all_quotas
if quota.resource in resources)
result_quotas = {quota.resource: quota for quota in all_quotas
if quota.resource in resources}
if len(result_quotas) != len(resources):
for resource in resources:
@ -94,9 +93,8 @@ class DbQuotaDriver(object):
"""
all_usages = QuotaUsage.find_all(tenant_id=tenant_id).all()
result_usages = dict((usage.resource, usage)
for usage in all_usages
if usage.resource in resources)
result_usages = {usage.resource: usage for usage in all_usages
if usage.resource in resources}
if len(result_usages) != len(resources):
for resource in resources:
# Not in the DB, return default value