**kwargs

Argumentos nomeados extra são recolhidos num dicionário. Lê-os com .get(key, default).

Sintaxe

def greet(name, **opts):
return opts.get("title", "bot") + " " + name
  • **opts só recolhe valores nomeados, não posicionais.

Exemplo

def greet(name, **opts):
    return opts.get("title", "bot") + " " + name

print(greet("Pip"))
print(greet("Pip", title="captain"))

Saída:

bot Pip
captain Pip

Erros comuns

  • Passar um segundo argumento posicional a uma função que só tem **opts para extras é um TypeError.

Pratique