7
class Test(object):
    def __init__(self, id, name):
        self.id = id
        self.name = name

def foo(d):
    return Test(**d)

# this works well
d = {'id': 'aaa', 'name': 'aaa-name'}
foo(d)
# this would not work well, because of parameter variations, a external para     add into dict d. 
d = {'id': 'aaa', 'name': 'aaa-name', 'test1': 'test1'}

# traceback
TypeError: __init__() got an unexpected keyword argument 'test1'

Is there any methods to ignore the parameter variations of dict d?

3
  • You pass kwargs, but you don't handle them. Use **kwargs or something in the init signature Commented Mar 8, 2016 at 8:14
  • 1
    What do you mean by "deal with" the extra keyword args? Ignore them? Use them to set attributes of the object? Something else? Commented Mar 8, 2016 at 8:20
  • Ignore extra keyword args. Commented Mar 8, 2016 at 8:27

2 Answers 2

13

You can make Test.__init__ accept an extra **kwargs

class Test(object):
    def __init__(self, id, name, **kwargs):
        self.id = id
        self.name = name
Sign up to request clarification or add additional context in comments.

6 Comments

That is half the answer. How to go from here?
@TimCastelijns I think that's enough, we can just ignore kwargs
Does it automatically assign to self from the keys in the dict?
@TimCastelijns: in all fairness the OP hasn't really explained what is meant by "deal with" the extra kwargs. At this point ignoring them is perfectly valid. Using them to set attributes on the object might also be valid.
@mhawke that's true. However in cases where it's not clear exactly what OP is asking, it's better to not answer at all until it's cleared up. Right now we can only guess
|
10

This will do the trick, simply update the self.__dict__

class Test(object):
    def __init__(self, id, name, **kwargs):
        self.id = id
        self.name = name
        self.__dict__.update(kwargs)

Example:

In[2]: class Test(object):
    def __init__(self, id, name, **kwargs):
        self.id = id
        self.name = name
        self.__dict__.update(kwargs)
In[3]: d = {'id': 'aaa', 'name': 'aaa-name', 'test1': 'test1'}
In[5]: t = Test(**d)
In[6]: t.id
Out[5]: 'aaa'
In[7]: t.name
Out[6]: 'aaa-name'
In[8]: t.test1
Out[7]: 'test1'

EDIT:

To ignore the extras just dont use the kwargs as in @wong2 answer:

class Test(object):
    def __init__(self, id, name, **kwargs):
        self.id = id
        self.name = name

4 Comments

Why not def __init__(self, **kwargs): self.__dict__.update(kwargs)?
@vaultah, he may want to force the id and the name to be forced int the params, so you really neead an id and a name
I want to ignore extra keyword args.
@Wilence see my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.