2

I have the following function:

def splot (self,what):
    df = pd.DataFrame((self.spec[what]).compute()).plot()
    plt.show()
    return df

I want to be able to pass parameters to the .plot() method when I call the splot function, like below:

def splot (self,what,arg=None):
    df = pd.DataFrame((self.spec[what]).compute()).plot(arg)
    plt.show()
    return df

So when I call splot, I give it two arguments: 'what' (a string), and the arguments I want the plot command to take.

However, this doesn't work: if I pass the argument as a string, I get a KeyError, and if not, it throws a variable error. I have a feeling that *args should be involved somewhere, but not sure how to use it in this instance.

1
  • Have you called method like this Obj.splot (what, arg="x") ? Commented Aug 13, 2018 at 11:26

1 Answer 1

1

Indeed, as you are guessing, you have to use the unpacking operator *. Here is an example of code close to yours in order to explain:

class myClass:

    def myPlot(self, x=None, y=None):
        print("myPlot:", x)
        print("myPlot:", y)

    def myFunc(self, what, *args, **kwargs):
        print(what)         # 'toto'
        print(args)         # tuple with unnamed (positional) parameters
        print(kwargs)       # dictionary with named (keyword) parameters
        self.myPlot(*args, **kwargs)   # use of * to unpack tuple and ** to unpack dictionary


myObject = myClass()
myObject.myFunc("toto", 4, 12)         # with positional arguments only
myObject.myFunc("toto", x = 4, y = 12) # with keyword arguments only
myObject.myFunc("toto", 4, y = 12)     # with both

So you should write your code like this:

def splot (self, what, *args, **kwargs):
    df = pd.DataFrame((self.spec[what]).compute()).plot(*args, **kwargs)
    plt.show()
    return df
Sign up to request clarification or add additional context in comments.

4 Comments

So that only brings along strings. What I'm trying to do is use the parameters of the pd.DataFrame.plot command. Is that just use **kwargs instead, or is it more complex?
@nothingtoseehere OK my first solution worked only with unnamed positional arguments. I have updated my post to work with named arguments either.
Yep, that works fine. Needs both *args and **kwargs for **kwargs to work for some reason, but it works.
Cool. if you use only keywords arguments, you don't need *args. Please consider accepting this answer (by clicking on Accept) if it answers your request.

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.