Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement set.discard(elem) #2633

Merged
merged 2 commits into from
Mar 29, 2024
Merged

Conversation

kmr-srbh
Copy link
Contributor

@kmr-srbh kmr-srbh commented Mar 28, 2024

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
Copy link
Contributor Author

@Shaikh-Ubaid this is the new PR.

Copy link
Collaborator

@Shaikh-Ubaid Shaikh-Ubaid left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks good. Thanks for this! Great work!

@Shaikh-Ubaid Shaikh-Ubaid merged commit eaf402c into lcompilers:main Mar 29, 2024
13 checks passed
@kmr-srbh kmr-srbh deleted the set-discard-method branch May 2, 2024 13:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants