Home

kwargs

Kwargs is a term used in Python to describe keyword arguments collected by a function. In a function definition, a parameter preceded by ** collects any keyword arguments that are not matched by other named parameters into a dictionary. The convention is to name this parameter kwargs, though the name is not required.

Inside the function, kwargs behaves like a standard dictionary. For example, given def connect(host, port=80, **kwargs):

Kwargs can be used in two directions. First, to accept arbitrary keyword arguments in a function, enabling

Common cautions include avoiding unexpected keys or conflicts with named parameters, and recognizing that keys in

you
can
call
connect('example.com',
timeout=5,
use_ssl=True).
Within
the
function,
kwargs['timeout']
yields
5,
and
kwargs['use_ssl']
yields
True.
Kwargs
is
also
commonly
used
to
implement
flexible
APIs,
wrappers,
or
decorators,
where
additional
options
may
be
passed
through
to
inner
calls.
forward
compatibility
and
extensibility.
Second,
to
pass
a
dictionary
of
options
as
keyword
arguments
to
another
function
using
unpacking
syntax,
e.g.,
options
=
{'timeout':
5};
connect('example.com',
**options).
A
function
may
be
defined
to
work
with
both
regular
parameters
and
kwargs,
and
it
can
also
be
combined
with
*args
to
handle
both
positional
and
keyword
arguments.
kwargs
are
strings
representing
parameter
names.
The
conventional
name
kwargs
is
widely
used,
but
any
valid
identifier
can
be
used.
Kwargs
provides
a
lightweight
mechanism
for
extensible
interfaces
and
wrapper
patterns
without
requiring
explicit
parameter
lists
for
every
option.