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

Syntactic sugar: Tree.has_data() #1465

Open
makukha opened this issue Sep 11, 2024 · 5 comments
Open

Syntactic sugar: Tree.has_data() #1465

makukha opened this issue Sep 11, 2024 · 5 comments

Comments

@makukha
Copy link

makukha commented Sep 11, 2024

Suggestion
Add new method Tree.has_data(data: str) -> bool to determine whether there is a token with given data.

Describe alternatives you've considered
This can be achieved with find_data() method, but is too verbose:

try:
    next(tree.find_data(data))
except StopIteration:
    has_data = False
else:
    has_data = True

compared to

tree.has_data(data)

Additional context
I'm ready to provide PR if you find this API enhancement reasonable.

@erezsh
Copy link
Member

erezsh commented Sep 11, 2024

I can suggest

has_data = bool(next(tree.find_data(data), False))

@erezsh
Copy link
Member

erezsh commented Sep 11, 2024

Another option is:

for _ in tree.find_data(data):
   # do if true
   break

I understand having a method would be a bit more ergonomic, but I feel like it's a bit too small to be worth adding.

But I'll leave it open, if more users would like this method, we can add it in.

@makukha
Copy link
Author

makukha commented Sep 11, 2024

I can suggest

has_data = bool(next(tree.find_data(data), False))

Thank you, this one is pretty close. I've forgotten about the next()'s default arg.

However, it will not work when next(tree.find_data(data)) == False itself.

@erezsh
Copy link
Member

erezsh commented Sep 11, 2024

Yeah. Honestly, I don't know why itertools doesn't have this method:

EMPTY = object()
def iter_is_empty(i) -> bool:
    return next(i, EMPTY) is EMPTY

@makukha
Copy link
Author

makukha commented Sep 11, 2024

It seems that people will tend to choose readability over performance:

has_data = bool(tuple(tree.find_data(data)))

(at least I will)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants