Python Glossary Русский

all Python 3Functionsterm

**kwargs

parameters

Accepts any number of keyword arguments as a dictionary.

Syntax

def f(**kwargs): ...

Inside the function kwargs is a plain dict, and since Python 3.6 (PEP 468) it preserves the order in which arguments were passed. In the signature **kwargs comes last; a double star at the call site, f(**d), does the reverse — spreading a dict into keyword arguments.

Examples

def show(**kwargs):
    for k, v in kwargs.items():
        print(k, v)
show(a=1, b=2)  # → a 1 / b 2
opts = {'timeout': 30, 'retry': 3}
show(**opts)  # → timeout 30 / retry 3 — ** раскладывает словарь обратно
def config(**kwargs):
    return kwargs
print(config(host='localhost', port=80))  # → {'host': 'localhost', 'port': 80}
def connect(host, port, **kwargs):
    print(host, port, kwargs)
connect('srv', 443, ssl=True)  # → srv 443 {'ssl': True}
def merge(base, **overrides):
    d = base.copy()
    d.update(overrides)
    return d
print(merge({'a': 1}, b=2))  # → {'a': 1, 'b': 2}
def forward(*args, **kwargs):
    print(args, kwargs)
forward(1, 2, x=3)  # → (1, 2) {'x': 3}
def all_args(a, *args, **kwargs):
    return a, args, kwargs
print(all_args(1, 2, 3, x=4))  # → (1, (2, 3), {'x': 4})

See also

Open in the full glossarydocs.python.orgReport an inaccuracy