python function *args and **kwargs with other specified keyword arguments

fmonegaglia picture fmonegaglia · Dec 22, 2012 · Viewed 8.8k times · Source

I have a Python class with a method which should accept arguments and keyword arguments this way

class plot:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def set_axis(self, *args, xlabel="x", ylabel="y", **kwargs):
        for arg in args:
            <do something>
        for key in kwargs:
             <do somethng else>

when calling:

plt = plot(x, y)
plt.set_axis("test1", "test2", xlabel="new_x", my_kwarg="test3")

I get the error: TypeError: set_axis() got multiple values for keyword argument 'xlabel'

Anyway if I set my method like

class plot:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def set_axis(self, xlabel="x", ylabel="y", *args, **kwargs):
        for arg in args:
            <do something>
        for key in kwargs:
             <do somethng else>

and call:

plt = plot(x, y)
plt.set_axis(xlabel="new_x", "test1", "test2", my_kwarg="test3")

I get SyntaxError: non-keyword arg after keyword arg, as I was expecting. What is wrong with the first case? How should I tell my method to accept any user argument and keyword argument, other than the default ones? (Hope my question is clear enough)

Answer

Jure C. picture Jure C. · Dec 22, 2012

You would use a different pattern:

def set_axis(self, *args, **kwargs):
    xlabel = kwargs.get('xlabel', 'x')
    ylabel = kwargs.get('ylabel', 'y')

This allows you to use * and ** while keeping the fallback values if keyword arguments aren't defined.