diff --git a/lib/spack/spack/spec.py b/lib/spack/spack/spec.py index e6985b5bfe3..1f9ba1e530b 100644 --- a/lib/spack/spack/spec.py +++ b/lib/spack/spack/spec.py @@ -3783,8 +3783,11 @@ def __contains__(self, spec): # if anonymous or same name, we only have to look at the root if not spec.name or spec.name == self.name: return self.satisfies(spec) - else: - return any(s.satisfies(spec) for s in self.traverse(root=False)) + try: + dep = self[spec.name] + except KeyError: + return False + return dep.satisfies(spec) def eq_dag(self, other, deptypes=True, vs=None, vo=None): """True if the full dependency DAGs of specs are equal.""" diff --git a/lib/spack/spack/test/spec_dag.py b/lib/spack/spack/test/spec_dag.py index 7ee0f0a44fc..2b5a18e3ea2 100644 --- a/lib/spack/spack/test/spec_dag.py +++ b/lib/spack/spack/test/spec_dag.py @@ -933,6 +933,11 @@ def test_indexing_prefers_direct_or_transitive_link_deps(): with pytest.raises(KeyError): root["a2"] + # Check consistency of __contains__ with __getitem__ + assert "z3 +through_z1" in root + assert "z3 +through_a1" in a1 + assert "a2" not in root + def test_getitem_sticks_to_subdag(): """Test that indexing on Spec by virtual does not traverse outside the dag, which happens in