Skip to content

[PyYAML] Require encoding for binary streams in dump and serialize - #17029

Open
ashishdhillon wants to merge 1 commit into
python:mainfrom
ashishdhillon:fix/16837-pyyaml-binary-stream-encoding
Open

ashishdhillon wants to merge 1 commit into
python:mainfrom
ashishdhillon:fix/16837-pyyaml-binary-stream-encoding

Conversation

@ashishdhillon

Copy link
Copy Markdown

Closes #16837

Summary

PyYAML's dump, dump_all, safe_dump, safe_dump_all, serialize, and serialize_all stubs previously accepted any _WriteStream[_YAMLObject] (_WriteStream[Any]) with encoding: str | None = None, which allowed binary streams such as io.BytesIO() without an explicit encoding even though PyYAML writes str and raises TypeError: a bytes-like object is required, not 'str' at runtime.

Changes

  • Added _TextWriteStreamWithEncoding protocol in stubs/PyYAML/yaml/emitter.pyi for text streams that expose an encoding attribute (such as io.StringIO and TextIO).
  • Updated stream overloads for serialize_all, serialize, dump_all, dump, safe_dump_all, and safe_dump in stubs/PyYAML/yaml/__init__.pyi:
    • stream: _WriteStream[str] when encoding: None = None (rejects binary streams without encoding).
    • stream: _WriteStream[bytes] | _TextWriteStreamWithEncoding when encoding: str (accepts binary streams and text streams with .encoding, rejects custom text writers without .encoding because PyYAML writes bytes to them).
    • stream: _TextWriteStreamWithEncoding when encoding: str | None = None (allows optional/nullable encoding for StringIO / TextIO).
  • Added regression test cases in stubs/PyYAML/@tests/test_cases/check_dump_streams.py.

Verification

  • .venv/bin/python tests/mypy_test.py stubs/PyYAML (Python 3.10–3.15, 108 files checked — passed)
  • .venv/bin/python tests/regr_test.py PyYAML (passed)
  • .venv/bin/python tests/pyright_test.py stubs/PyYAML (0 errors, 0 warnings — passed)
  • .venv/bin/python tests/stubtest_third_party.py PyYAML (passed)
  • .venv/bin/python tests/check_typeshed_structure.py & .venv/bin/ruff check stubs/PyYAML (passed)

@github-actions

github-actions Bot commented Dec 5, 2026

Copy link
Copy Markdown
Contributor

According to mypy_primer, this change has no effect on the checked open source code. 🤖🎉

This branch has not been deployed

No deployments
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.

[PyYAML] Dump and serialize stubs accept binary streams without an encoding

1 participant