Skip to content

Comments

Accept str subclasses in SafeRepresenter (fixes support of enum.StrEnum)#901

Open
1ace wants to merge 2 commits intoyaml:mainfrom
1ace:StrEnum
Open

Accept str subclasses in SafeRepresenter (fixes support of enum.StrEnum)#901
1ace wants to merge 2 commits intoyaml:mainfrom
1ace:StrEnum

Conversation

@1ace
Copy link

@1ace 1ace commented Nov 1, 2025

For instance, Python 3.11 introduced enum.StrEnum, which subclasses str, and should be used as such.

@1ace
Copy link
Author

1ace commented Nov 1, 2025

@nitzmahone could you run CI on this change please? I haven't been able to run the tests locally (they always pick up the installed yaml instead of the local one), so it's possible this might be broken or not even work 🙃

Edit: I managed to make it work with a little PYTHONPATH=$PWD/lib magic, and I can see that it doesn't work because it matches object before going to the subclasses path; I'm going to exclude object and handle it separately since everything is an object

@1ace
Copy link
Author

1ace commented Nov 1, 2025

Also, for anyone coming across this PR: you can work around this bug with this line in your code, before your call to yaml.dump():

yaml.add_multi_representer(StrEnum, yaml.representer.SafeRepresenter.represent_str)

For instance, Python 3.11 introduced `enum.StrEnum`, which subclasses
`str`, and should be used as such.
@1ace
Copy link
Author

1ace commented Nov 1, 2025

OK, it now works (and passes all the tests), but it's a new approach that only fixes str subclasses; this solves the current problem, but doesn't fix other subclasses, but also I realized that non-string objects might be a minefield to serialize properly and we probably don't want to accidentally pick the wrong way to do it.

Given the narrow solution used now, I don't expect any regressions should be possible 😇🤞

@1ace 1ace changed the title Handle subclasses in representer (fixes support of enum.StrEnum) Accept str subclasses in SafeRepresenter (fixes support of enum.StrEnum) Nov 1, 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