Skip to content

How to bypass unknown keys? #16

@agusmakmun

Description

@agusmakmun

Hello @onyb, can you please help me how to bypass unkonwn keys?

For example, we only accepted 3 fields:

class Book(Model):
    title = Field()
    authors = Field()
    price = Field()

But in another case, the payloads become dynamic, where allow_trial is not defined in the field yet.
It can be 1-or more undefined fields will be come. and not using Field(default=xxx) as approach.

payloads = {
    "title": "Hello world",
    "authors": [],
    "price": 21.5,
    "allow_trial": True,  # here is
}

book = Book(**payloads)

So, based on above, it will raise an error;

TypeError: __init__() got an unexpected keyword argument 'allow_trial'

Meanwhile, in my case, I just need to bypass the allow_trial field, and keep running with adding print/logging error info.

I have tried to modify the __new__(...) function, but seems still got the same error:

import attr

class Book(Model):
    ...


    def __new__(cls, *args, **kwargs):
        acceptable_keys = [field.name for field in attr.fields(cls)]
        for key, value in kwargs.copy().items():
            if key not in acceptable_keys:
            kwargs.pop(key)  # remove unknown key
        return super().__new__(cls, *args, **kwargs)

OR, the second option is to allow that unknown allow_trial field.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions