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

TypeError in bisect when called with key argument #117848

Closed
michikoba opened this issue Apr 13, 2024 · 4 comments
Closed

TypeError in bisect when called with key argument #117848

michikoba opened this issue Apr 13, 2024 · 4 comments
Labels
type-bug An unexpected behavior, bug, or error

Comments

@michikoba
Copy link

michikoba commented Apr 13, 2024

Bug report

Bug description:

bisect functions raise TypeError when called with key argument.
Here is a minimum code to reproduce the issue:

import bisect
import operator

a = [('one', 1), ('two', 2)]
print(bisect.bisect(a, ('one', 1), key=operator.itemgetter(0)))

This results in the following error:

Traceback (most recent call last):
  File "/path/to/bisect_test.py", line 5, in <module>
    print(bisect.bisect(a, ('one', 1), key=operator.itemgetter(0)))
          ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: '<' not supported between instances of 'tuple' and 'str'

It seems that picking an item in a tuple has a problem.

CPython versions tested on:

3.12

Operating systems tested on:

macOS

@michikoba michikoba added the type-bug An unexpected behavior, bug, or error label Apr 13, 2024
@nineteendo
Copy link
Contributor

nineteendo commented Apr 13, 2024

You need to apply key() to the element:

key=operator.itemgetter(0)
print(bisect.bisect(a, key(('one', 1)), key=key))

@nineteendo
Copy link
Contributor

See #20556 (comment)

@nineteendo
Copy link
Contributor

nineteendo commented Apr 13, 2024

@AlexWaygood, could you close this? This works as intended. Sorry for the ping.

@michikoba
Copy link
Author

@nineteendo Thank you for your comment.
Now I understand that giving the field to be compared is better than the entire record in bisect search.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type-bug An unexpected behavior, bug, or error
Projects
None yet
Development

No branches or pull requests

2 participants