python: use the setdefault method on dict

It allows more concise code and skips some key lookups.
This commit is contained in:
Ben Boeckel 2015-10-15 09:18:16 -04:00
parent f76b3890ff
commit 9d90cb6962
3 changed files with 7 additions and 16 deletions

View file

@ -87,10 +87,7 @@ def index_by(objects, *funcs):
result = {}
for o in objects:
key = f(o)
if key not in result:
result[key] = [o]
else:
result[key].append(o)
result.setdefault(key, []).append(o)
for key, objects in result.items():
result[key] = index_by(objects, *funcs[1:])

View file

@ -239,12 +239,10 @@ def patch(pkg, url_or_filename, level=1, when=None):
when = pkg.name
when_spec = parse_anonymous_spec(when, pkg.name)
if when_spec not in pkg.patches:
pkg.patches[when_spec] = [Patch(pkg.name, url_or_filename, level)]
else:
cur_patches = pkg.patches.setdefault(when_spec, [])
# if this spec is identical to some other, then append this
# patch to the existing list.
pkg.patches[when_spec].append(Patch(pkg.name, url_or_filename, level))
cur_patches.append(Patch(pkg.name, url_or_filename, level))
@directive('variants')

View file

@ -73,10 +73,8 @@ def update(self, spec):
for provided_spec, provider_spec in pkg.provided.iteritems():
if provider_spec.satisfies(spec, deps=False):
provided_name = provided_spec.name
if provided_name not in self.providers:
self.providers[provided_name] = {}
provider_map = self.providers[provided_name]
provider_map = self.providers.setdefault(provided_name, {})
if not provided_spec in provider_map:
provider_map[provided_spec] = set()
@ -133,9 +131,7 @@ def _cross_provider_maps(self, lmap, rmap):
if lp_spec.name == rp_spec.name:
try:
const = lp_spec.copy().constrain(rp_spec,deps=False)
if constrained not in result:
result[constrained] = set()
result[constrained].add(const)
result.setdefault(constrained, set()).add(const)
except spack.spec.UnsatisfiableSpecError:
continue
return result