[Set] Raise KeyError on empty set.pop() (#152907)

Pull Request resolved: https://github.com/pytorch/pytorch/pull/152907
Approved by: https://github.com/anijain2305
ghstack dependencies: #150792, #152987, #152988, #152904, #152901, #152902, #152903, #152905, #152906, #152989
This commit is contained in:
Guilherme Leobas 2025-05-15 22:47:18 -03:00 committed by PyTorch MergeBot
parent 5964cb5eb1
commit 053025494f
3 changed files with 18 additions and 1 deletions

View File

@ -1681,6 +1681,18 @@ class FunctionTests(torch._dynamo.test_case.TestCase):
else:
return a * b
@make_test
def test_set_pop_raise_KeyError(a, b):
s = set()
try:
s.pop()
except KeyError:
return a + b
except Exception:
return a - b
else:
return a * b
@make_test
def test_set_issubset(a, b):
vals1 = {"a", "b", "c"}

View File

@ -765,7 +765,12 @@ class SetVariable(ConstDictVariable):
assert not kwargs
assert not args
# Choose an item at random and pop it via the Dict.pop method
result = self.set_items.pop().vt
try:
result = self.set_items.pop().vt
except KeyError as e:
raise_observed_exception(
KeyError, tx, args=list(map(ConstantVariable.create, e.args))
)
super().call_method(tx, name, (result,), kwargs)
return result
elif name == "isdisjoint":