Skip to content

gh-116436: Improve error message when TypeError occurs during dict update#116443

Merged
hauntsaninja merged 7 commits into
python:mainfrom
hauntsaninja:gh116436
Apr 30, 2025
Merged

gh-116436: Improve error message when TypeError occurs during dict update#116443
hauntsaninja merged 7 commits into
python:mainfrom
hauntsaninja:gh116436

Conversation

@hauntsaninja

@hauntsaninja hauntsaninja commented Mar 6, 2024

Copy link
Copy Markdown
Contributor

The example I gave in the issue now looks like:

Traceback (most recent call last):
  File "/Users/shantanu/dev/cpython/z.py", line 8, in <module>
    x.update([foo() for _ in range(3)])
    ~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/shantanu/dev/cpython/z.py", line 4, in foo
    yield random.randint(100)  # oops, only passed in one argument
          ~~~~~~~~~~~~~~^^^^^
TypeError: Random.randint() missing 1 required positional argument: 'b'
Cannot convert dictionary update sequence element #0 to a sequence

Previously it was just:

Traceback (most recent call last):
  File "/Users/shantanu/dev/cpython/z.py", line 7, in <module>
    dict([foo() for _ in range(3)])
TypeError: cannot convert dictionary update sequence element #0 to a sequence

@hauntsaninja

Copy link
Copy Markdown
Contributor Author

Hopefully this is a good use of exception notes, since it's just adding context. If not, maybe something with PyException_SetCause works

Comment thread Objects/dictobject.c

/* Convert item to sequence, and verify length 2. */
fast = PySequence_Fast(item, "");
fast = PySequence_Fast(item, "object is not iterable");

@hauntsaninja hauntsaninja Mar 6, 2024

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Technically, I guess PyObject_GetIter has a different error message for the edge case where __iter__ exists but returns a non-iterator.

I think nicest thing would be to change PySequence_Fast so that if m is NULL it doesn't clobber the message

@sobolevn sobolevn changed the title gh-116436: Improve error message when TypeError occurs during dict uupdate gh-116436: Improve error message when TypeError occurs during dict update Mar 7, 2024
@hauntsaninja
hauntsaninja requested a review from pablogsal April 23, 2024 02:15
@python-cla-bot

python-cla-bot Bot commented Apr 18, 2025

Copy link
Copy Markdown

All commit authors signed the Contributor License Agreement.

CLA signed

@hauntsaninja
hauntsaninja merged commit 7e8b153 into python:main Apr 30, 2025
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.

1 participant