在 attrs 自动生成的 init 方法签名中禁用前导下划线删除

Disable leading underscore removal in attrs auto-generated init method signature

attr strips 生成的 __init__ 方法的属性名称前导下划线。有没有办法为特定属性覆盖它,而不是完全禁用 class 的自动生成的初始化方法?

我想用attr class来表示MongoDB个文档,在Python中是用_id键记录的字典唯一身份。我希望能够有一个 from_db(cls, doc) class 方法,它比 return cls(**doc) 多一点,但是 _id 的存在导致“TypeError: init() 得到了一个意外的关键字参数 '_id'”。现在,我通过声明 `_id: attr.ib(init=False, default=None) 和 having:

来解决这个问题
@classmethod from_db(cls, doc):
    _id = doc["_id"]
    del(doc["_id"])
    obj = cls(**doc)
    obj._id = _id
    return obj

但这似乎真的很麻烦。有没有更好的方法?

目前不可能,抱歉。

参见:

从长远来看,您可能 运行 遇到更复杂的异常,然后像 cattrs 这样的工具就更有意义了。