[英]json.dumps() encodes StrEnum with custom __new__ to empty string
I have an enum similar to the following:我有一个类似于以下的枚举:
from enum import Enum
class Currencies(str, Enum):
EURO = ("EUR", True)
YEN = ("JPY", False)
supports_decimals: bool
def __new__(cls, value: str, supports_decimals: bool):
obj = super().__new__(cls)
obj._value_ = value
setattr(obj, "supports_decimals", supports_decimals)
return obj
This allows things like:这允许以下内容:
>>> Currencies.EURO.value
'EUR'
>>> Currencies.EURO.supports_decimals
True
>>> f"{Currencies.EURO}"
'EUR'
However:然而:
>>> import json
>>> json.dumps(Currencies.EUR)
'""'
This would work if my enum had simple string members instead of tuples, but instead it results in empty strings, and since the enum's members are seen as str
, a custom encoder class doesn't call .default()
on them at all, so I can't define a custom encoding for them.如果我的枚举有简单的字符串成员而不是元组,这将起作用,但它会导致空字符串,并且由于枚举的成员被视为
str
,因此自定义编码器 class 根本不会在它们上调用.default()
,所以我无法为它们定义自定义编码。
The problem likely comes down to str.encode()
, because indeed:问题可能归结为
str.encode()
,因为确实:
>>> Currencies.EUR.encode()
b''
But even knowing that, I don't know how I could instruct json.dumps()
to use the member's _value_
.但即使知道这一点,我也不知道如何指示
json.dumps()
使用成员的_value_
。 I tried overriding encode()
and that makes Currencies.EUR.encode()
work, but json.dumps()
still returns an empty string.我尝试覆盖
encode()
并且这使得Currencies.EUR.encode()
工作,但json.dumps()
仍然返回一个空字符串。
Note that I'd rather keep the enum a str, Enum
because turning it into a simple Enum would complicate other parts of my application.请注意,我宁愿将 enum 保留为
str, Enum
因为将其转换为简单的 Enum 会使我的应用程序的其他部分复杂化。
Your enum instances are empty strings .您的枚举实例是空字符串。
obj = super().__new__(cls)
makes an instance that is an empty string. obj = super().__new__(cls)
创建一个空字符串实例。
Make a nonempty string:创建一个非空字符串:
obj = super().__new__(cls, value)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.