Why this unpacking of arguments does not work?

user3056783 picture user3056783 · Apr 11, 2014 · Viewed 55.1k times · Source

I get an error type object argument after ** must be a mapping, not tuple.

I have this code: create_character = player.Create(**generate_player.generate())

this is player.py module:

class Create(object):

    def __init__(self,name,age,gender):
        self.name = name
        self.age = age
        self.gender = gender

this is generate_player.py module:

import prompt

def generate():

    print "Name:"
    name = prompt.get_name()
    print "Age:"
    age = prompt.get_age()
    print "Gender M/F:"
    gender = prompt.get_gender()

    return name, age, gender

The prompt module is just bunch of raw_inputs that return either string or integers (int for age).

Why is it returning tuples? When I run print type in generate_player module I get string, int, string for my arguments.

Answer

Martijn Pieters picture Martijn Pieters · Apr 11, 2014

The ** syntax requires a mapping (such as a dictionary); each key-value pair in the mapping becomes a keyword argument.

Your generate() function, on the other hand, returns a tuple, not a dictionary. You can pass in a tuple as separate arguments with similar syntax, using just one asterisk:

create_character = player.Create(*generate_player.generate())

Alternatively, fix your generate() function to return a dictionary:

def generate():
    print "Name:"
    name = prompt.get_name()
    print "Age:"
    age = prompt.get_age()
    print "Gender M/F:"
    gender = prompt.get_gender()

    return {'name': name, 'age': age, 'gender': gender}