pyyaml icon indicating copy to clipboard operation
pyyaml copied to clipboard

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

Open 1ace opened this issue 1 month ago • 3 comments

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

1ace avatar Nov 01 '25 12:11 1ace

@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 avatar Nov 01 '25 12:11 1ace

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)

1ace avatar Nov 01 '25 13:11 1ace

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 avatar Nov 01 '25 16:11 1ace