Maya / Python noobie question about **kwargs

Hello, I just got into python in the last few months and trying to write an auto rigger.
currently, I have a ctrl creation class and I would like to pass arguments like this.

def example(**kwargs):

kw = ['{0} = {1}'.format(key, value) for key, value in kwargs.items()]
cmds.polySphere(kw)

example(n= ‘hello’, r=2)

I think it mainly doesn’t work due to formatting the kwargs.

Any help would be appreciated.

Close, just missed a bracket:

 ["{0}={1}".format(k, v), for (k, v) in kwargs.items()]

Other ways:

map(lambda n: "{0}={1}".format(*n), kwargs.items())

Is that what you’re aiming for?

def example(**kwargs):
    kw = ['{0} = {1}'.format(key, value) for key, value in kwargs.items()]
    cmds.polySphere(kw)

example(n= ‘hello’, r=2)

Because the proper way to pass kwargs through to another function would be:

def example(**kwargs):
    cmds.polySphere(**kwargs)

example(n= ‘hello’, r=2)

Here’s some documentation on unpacking arguments - its a neat mechanic of python:

This code:

kw = ['{0} = {1}'.format(key, value) for key, value in kwargs.items()]
cmds.polySphere(kw)

Would probably throw an error because its evaluating to pass a list of strings to the method - when in fact it need argument assignment - key, value pairs. (When default arguments are passed)

The * and ** prefixes unpack either a list of values of a key, value pair i.e. a dictionary/hash table. This is why @bob.w has it in their example.

If a method has both default and non-default arguments you can pass both using the unpacking mechanic.


args = [10, 20, 30]
kwargs = {"a":1, "b":2, "c":3}

my_method(*args, **kwargs)

1 Like

your answer got me exactly what I was trying to do. My first attempt was pretty close, before i tried to format it.

def example(**kwargs):
cmds.polySphere(kwargs)

example(n= ‘hello’, r=2)

I just didn’t understand how to unpack the arguments properly. Thank you for the help.

awesome thank you for the documentation. When I was looking for documentation on how to do it i just wasn’t asking the right question. Thanks for your help very much appreciated.

Glad you got it sorted out.