lcompilers / lpython

Python compiler
https://lpython.org/
Other
1.37k stars 157 forks source link

Implement `set.discard(elem)` #2633

Closed kmr-srbh closed 3 months ago

kmr-srbh commented 3 months ago

The official Python documentation describes set.discard(elem) as:

Remove element elem from the set if it is present.

and set.remove(elem) as:

Remove element elem from the set. Raises KeyError if elem is not contained in the set.

Hence, it is obvious that both the functions do the same work, but differ only with throwing an error for an absent key. As we already had the infrastructure for set.remove, it was easy to base and implement set.discard on top of that.

The idea is simple - utilize the same back-end function, but do not throw an error for set.discard.

Working

from lpython import i32

my_set: set[i32] = {1, 2, 3, 4}
my_set.discard(1)
print(len(my_set))
my_set.remove(1)
(lp) saurabh-kumar@Awadh:~/Projects/System/lpython$ ./src/bin/lpython ./examples/example.py
3
KeyError: The set does not contain the specified element

The changed length and KeyError for set.remove prove the normal working of set.discard.

Handling KeyError

set.discard

from lpython import i32

my_set: set[i32] = {1, 2, 3, 4}
my_set.discard(100012345678901234567890)
(base) saurabh-kumar@Awadh:~/Projects/System/lpython$ ./src/bin/lpython ./examples/example.py
(base) saurabh-kumar@Awadh:~/Projects/System/lpython$ 

set.remove

from lpython import i32

my_set: set[i32] = {1, 2, 3, 4}
my_set.remove(100012345678901234567890)
(base) saurabh-kumar@Awadh:~/Projects/System/lpython$ ./src/bin/lpython ./examples/example.py
KeyError: The set does not contain the specified element
kmr-srbh commented 3 months ago

@Shaikh-Ubaid this is the new PR.