Skip to content

Fix pyyaml converter crashing on non-enum str subclasses - #804

Open
Debasishhh wants to merge 4 commits into
python-attrs:mainfrom
Debasishhh:pyyaml-str-subclasses
Open

Debasishhh wants to merge 4 commits into
python-attrs:mainfrom
Debasishhh:pyyaml-str-subclasses

Conversation

@Debasishhh

Copy link
Copy Markdown

The PyYAML preconf converter's str unstructure hook assumes any str subclass is a string enum and returns v.value. Any other subclass crashes:

from attrs import define
from markupsafe import Markup
from cattrs.preconf.pyyaml import make_converter

@define
class Page:
    title: str

make_converter().dumps(Page(Markup("<b>x</b>")))
# AttributeError: 'Markup' object has no attribute 'value'

Returning the value unchanged isn't enough, because yaml.safe_dump refuses str subclasses too. So the hook now keeps the enum path and turns any other subclass into a plain str. I moved it into a small named function since the one-line conditional was getting hard to read.

Added a test with a plain class MyStr(str) that checks the unstructured value is an exact str and that dumps/loads round-trips. The full test suite passes locally, and ruff check/ruff format are clean.

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.

1 participant