Complete Guide to Python Variable Arguments (varargs, args, kwargs)

July 16, 2019

Variable positional arguments: *args

Send variable positional arguments

import time

def _send_message(timestamp, message):
    print(f"{int(timestamp)}: {message}")


def log(*args):
    _send_message(*args)

log(time.time(), 'Hello')

Variable named arguments: **kwargs

def log(**kwargs):
    send_message(**kwargs)

log(timestamp=time.time(), message='Hello')

Variable named and positional arguments

def log(*args, **kwargs):
    send_message(*args, **kwargs)

log(time.time(), message='Hello')

Modify **kwargs

def log(*args, **kwargs):
    kwargs['timestamp'] = time.time()
    send_message(*args, **kwargs)

log(message='Hello')

Mix with known arguments

def log(timestamp, *args, **kwargs):
    send_message(timestamp, *args, **kwargs)

log(time.time(), message='Hello')
def log(*args, **kwargs):
    for k,v in enumerate(args):
        print(f"{k}={v}")

    for k,v in kwargs.items():
        print(f"{k}={v}")

log(time.time(), message='Hello')
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.