0

I'm trying to implement a function with 2 arguments and an additional 3rd arbitrary keyword argument using **kwarg formatting, as below:

def build_profile(first_name, last_name, **additional_info):
    """ Building a user profile """
    profile = {}
    profile['First name'] = first_name
    profile['Last name'] = last_name
    for key, value in additional_info.items():
        profile[key.title()] = value.title()
    return profile

build_profile("x", 'y', 'x', 'y', 'x', 'y')

However, this produces the error:

TypeError: build_profile() takes 2 positional arguments but 6 were given

I managed to reproduce this error in isolation using the following code:

def x(**y):
    print(y)

Output:

x(1,2,3,4,5)

This generates the same response:

TypeError: x() takes 0 positional arguments but 1 was given

This has lead me to conclude that I either:

  1. Have an issue with my python configuration (running 3.6.4 in Spyder) or
  2. I'm missing something blindingly obvious.
nekomatic
  • 5,988
  • 1
  • 20
  • 27
  • 1
    Possible duplicate of [What does \*\* (double star/asterisk) and \* (star/asterisk) do for parameters?](https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters) – Taku Apr 26 '18 at 06:10

2 Answers2

3

The **kwargs syntax in a function signature is for accepting an arbitrary number of keyword arguments, i.e. arguments passed in like f(name=value).

def f(**kwargs):
    # kwargs is a dict here

The syntax used for accepting an arbitrary number of positional arguments looks like *args:

def f(*args):
    # args is a tuple here

It's the * and ** which make the syntax, this choice of names is just a convention - you can use other names if you want. You may also specify both.

def f(*splat, **splattysplat):
    ...
wim
  • 338,267
  • 99
  • 616
  • 750
1

Here are examples if you want minimalistic, understandable approaches.

>>> def x(*args):
...    for arg in args:
...        print(arg)

>>> x(1, 2, 3)
1
2
3

>>> def x(**kwargs):
...    for k, v in kwargs.items():
...        print(k, v)

>>> x(name='john', surname='wick')
name john
surname wick
BcK
  • 2,548
  • 1
  • 13
  • 27