简体   繁体   English

自定义数据类 asdict 键名

[英]Customise dataclass asdict keynames

How can I create a dataclass that has a custom dict representation?如何创建具有自定义 dict 表示的数据类?

Example dict output:示例字典 output:

{
    '$1': 'foo',
    '$2': 'bar',
    '$3': 'baz'
}

Obviously I can't have dataclass显然我不能有数据类

@dataclass
class Foo:
    $1: str
    ...

I would need it represented as我需要它表示为

@dataclass
class Foo:
    one: str
    ...

for example, but I would like dataclasses.asdict(foo) to return with the "$1" etc. key names.例如,但我希望dataclasses.asdict(foo)以“$1”等键名返回。

Also it would be great if如果

x = {
    '$1': 'foo',
    '$2': 'bar',
    '$3': 'baz'
}
foo = Foo(**x)
assert foo.one == 'foo'
assert foo.two == 'bar'
assert foo.three == 'baz'

worked工作过

You can simply pass your own dict_factory argument, which uses your mapping to construct the dict .您可以简单地传递您自己的dict_factory参数,该参数使用您的映射来构造dict

@dataclass
class Foo:
    one: str

def factory(kv_pairs):
    m = {
        'one': '$1',
        # etc
    }
    return {m.get(k): v for k, v in kv_pairs}


f = Foo("foo")
assert dataclasses.asdict(f, dict_factory=factory) == {'$1': 'foo'}

For initializing the class, I would go with a custom class method.为了初始化 class,我将使用自定义 class 方法来初始化 go。

m = {'one': '$1'}
m_inv = {v: k for k, v in m.items()}

@dataclass
class Foo:
    one: str

    @classmethod
    def from_dollar_vars(cls, **kwargs):
        return cls(**{m_inv[k]: v for k, v in kv_pairs})

def factory(kv_pairs):
    return {m[k]: v for k, v in kv_pairs}

x = {'$1': 'foo'}
f = Foo.from_dollar_vars(**x)
assert dataclasses.asdict(f, dict_factory=factory) == x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM