Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add value representer to enum.StrEnum type #839

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions lib/yaml/representer.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from .error import *
from .nodes import *

import datetime, copyreg, types, base64, collections
import datetime, copyreg, types, base64, collections, sys

class RepresenterError(YAMLError):
pass
Expand Down Expand Up @@ -145,7 +145,7 @@ def represent_none(self, data):
return self.represent_scalar('tag:yaml.org,2002:null', 'null')

def represent_str(self, data):
return self.represent_scalar('tag:yaml.org,2002:str', data)
return self.represent_scalar('tag:yaml.org,2002:str', str(data))

def represent_binary(self, data):
if hasattr(base64, 'encodebytes'):
Expand Down Expand Up @@ -236,6 +236,12 @@ def represent_undefined(self, data):
SafeRepresenter.add_representer(str,
SafeRepresenter.represent_str)

if sys.version_info >= (3, 11):
from enum import StrEnum

SafeRepresenter.add_multi_representer(StrEnum,
SafeRepresenter.represent_str)

SafeRepresenter.add_representer(bytes,
SafeRepresenter.represent_binary)

Expand Down
14 changes: 14 additions & 0 deletions tests/test_dump_load.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import sys

import pytest
import yaml

Expand All @@ -13,3 +15,15 @@ def test_load_no_loader():

def test_load_safeloader():
assert yaml.load("- foo\n", Loader=yaml.SafeLoader)


def test_dump_str_enum():
if sys.version_info < (3, 11):
return

from enum import StrEnum

class ContentType(StrEnum):
YAML = "YAML"

assert yaml.load(yaml.dump(ContentType.YAML, Dumper=yaml.SafeDumper), Loader=yaml.SafeLoader) == ContentType.YAML