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

Underscore attribute ruins initiating an instance from dict data #263

Closed
MacHu-GWU opened this issue Oct 12, 2017 · 3 comments
Closed

Underscore attribute ruins initiating an instance from dict data #263

MacHu-GWU opened this issue Oct 12, 2017 · 3 comments

Comments

@MacHu-GWU
Copy link

@attr.s
class User(object):
    _id = attr.ib()
    name = attr.ib()

doc = {"_id": 1, "name": "Alice"}

when working with mongodb, how could I create instance for this from mongodb document?

because we know that User(**doc) doesn't work due to the underscore.

@Tinche
Copy link
Member

Tinche commented Oct 12, 2017

Well there are many ways. You could try this:

@attr.s
class User(object):
    _id = attr.ib()
    name = attr.ib()

    @classmethod
    def from_mongo(cls, doc):
        return cls(**{k if not k.startswith('_') else k[1:]: v for k, v in doc.items()})

@hynek
Copy link
Member

hynek commented Oct 14, 2017

Questions like this are being asked basically once week now. I’m afraid I’ll have to write a lot more docs.

@hynek
Copy link
Member

hynek commented Apr 25, 2018

fixed in #370

@hynek hynek closed this as completed Apr 25, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants