Using **kwargs in a Python function

Viewed 120

Consider a method like the one below:

    def find_missing(self, **kwargs):
        if save == True:
            tmp = find_one_missing(self.data)
            tmp.to_csv(path)
        else:
            return find_one_missing(self.data)

What I am trying to achieve is the variables save and path to be kwargs, whereby the use can specify either

x.find_missing()

which will return the output of the find_one_missing() function, or alternatively the user can insert

x.find_missing(save=True, path=user_string_pathway)

and the output will be automatically saved to a location. How can I do this?

1 Answers

Call:

find_missing(save=True, path="/path/...")

Access the value using kwargs['save'] and kwargs['path']

def find_missing(self, **kwargs):
        if kwargs['save'] == True:
            tmp = find_one_missing(self.data)
            tmp.to_csv(kwargs['path'])
        else:
            return find_one_missing(self.data)
Related