user1971598
user1971598

Reputation:

Setting default values for arbitrary number of keyword arguments

Say I have:

class Example(object):

    def __init__(self, table = None, rows = None, cats = None, **kwargs)
        self.table = table
        self.rows = rows
        self.cats = cats

My question is, how can I make kwargs have a default value of None, for all the kwargs? kwargs is a dict, right...?

Upvotes: 0

Views: 84

Answers (2)

Stefano Sanfilippo
Stefano Sanfilippo

Reputation: 33046

Yes is a dictionary. As such, it supports the get() method. Just like using [] but will return None (or a custom value) instead of raising a KeyError.

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599628

That makes no sense. The reason to use kwargs at all is because you're not sure what keyword arguments are going to be passed in. So what would it mean for an unknown keyword argument to have a default value?

You can use a default when you ask for a value from kwargs by simply using the dictionary .get() method, if that's what you're asking:

value_that_might_be_missing = kwargs.get('myvalue', 'mydefault')

otherwise I really can't imagine what you would want.

Upvotes: 4

Related Questions