2

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?

4
  • You need to use kwargs["save"] to access it (after checking to see if it's present). Similarly for path. Commented Oct 15, 2020 at 14:00
  • Another alternative is to remove the keyword argument, and instead provide default values, e.g. def find_missing(self, save=None, path=None): Then you could access the arguments normally. Commented Oct 15, 2020 at 14:03
  • 1
    Why are you using **kwargs at all? That's something you use if you want your function to accept arbitrary keyword arguments. It looks like you're looking for default values and/or keyword-only argument syntax. Commented Oct 15, 2020 at 14:03
  • 2
    Also, interface suggestion: consider using a single save_to argument, or just removing the save argument and keeping path. You don't need two separate arguments, and using one argument avoids problems with people passing inconsistent arguments. Commented Oct 15, 2020 at 14:05

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

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.