attr
strips leading underscore from attribute names for the generated __init__
method . Is there a way to override that for a particular attribute, short of disabling auto-generated initialization method for the class entirely?
I'd like to use attr
class to represent MongoDB documents, which in Python are dictionaries with the _id
key to record the unique id. I was hoping to be able to have a from_db(cls, doc)
class method that's little more than return cls(**doc)
, but the presence of _id
causes "TypeError: init() got an unexpected keyword argument '_id'". Right now, I work around it by declaring `_id: attr.ib(init=False, default=None), and having:
@classmethod from_db(cls, doc):
_id = doc["_id"]
del(doc["_id"])
obj = cls(**doc)
obj._id = _id
return obj
but that seems really klugey. Is there a better way?
Currently not possible, sorry.
See:
Long-term you'll probably run into more complicated exceptions and then tools like cattrs make more sense.