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

Jul 16, 2019

Variable positional arguments: *args

Send variable positional arguments

import timedef _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')

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.