Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I copy **kwargs to self?

Tags:

Is there a way that I can define __init__ so keywords defined in **kwargs are assigned to the class?

For example, if I were to initialize a ValidationRule class with ValidationRule(other='email'), the value for self.other should be added to the class without having to explicitly name every possible kwarg.

class ValidationRule:
    def __init__(self, **kwargs):
        # code to assign **kwargs to .self
like image 266
mpen Avatar asked Mar 29 '10 05:03

mpen


People also ask

How do you pass Kwargs in a class Python?

Use the Python **kwargs parameter to allow the function to accept a variable number of keyword arguments. Inside the function, the kwargs argument is a dictionary that contains all keyword arguments as its name-value pairs. Precede double stars ( ** ) to a dictionary argument to pass it to **kwargs parameter.

What is the correct way to use the Kwargs statement?

The double asterisk form of **kwargs is used to pass a keyworded, variable-length argument dictionary to a function. Again, the two asterisks ( ** ) are the important element here, as the word kwargs is conventionally used, though not enforced by the language.

How do you get arguments from Kwargs?

The special syntax **kwargs in function definitions in python is used to pass a keyworded, variable-length argument list. We use the name kwargs with the double star. The reason is that the double star allows us to pass through keyword arguments (and any number of them).

How do you give Kwargs in Python?

**kwargs allows us to pass a variable number of keyword arguments to a Python function. In the function, we use the double-asterisk ( ** ) before the parameter name to denote this type of argument.


1 Answers

I think somewhere on the stackoverflow I've seen such solution. Anyway it can look like:

class ValidationRule:
    __allowed = ("other", "same", "different")
    def __init__(self, **kwargs):
        for k, v in kwargs.iteritems():
            assert( k in self.__class__.__allowed )
            setattr(self, k, v)

This class will only accept arguments with a whitelisted attribute names listed in __allowed.

like image 171
ony Avatar answered Oct 22 '22 23:10

ony