Understanding *args and **kwargs

args and kwargs are hard. They are confusing, and tricky when you are learning python. Even experienced developers can be tripped up by them. Learn how to expand and collapse lists and dictionaries for args and kwargs.
Download HD Version next video: django-avatar
def print_args(d1, d2, d3):
    print(d1, d2, d3)

data = ('foo', 'bar', 'baz')
print_args(*data)
>>> foo bar baz

def print_args(*args):
    for arg in args:
        print(arg)
print_args(1, 2, 3)
>>> 1
>>> 2
>>> 3

def print_args(*args):
    print(args)
print_args(1, 2, 3)
>>> (1, 2, 3)

def print_args(a, b, c, *args):
    print(a, b, c, args)
print_args(1, 2, 3, 4, 5)
>>> 1 2 3 (4, 5)


def print_kwargs(**kwargs):
    print(kwargs)
print_kwargs(foo='bar', hello='world')
>>> {'foo': 'bar', 'hello': 'world'}

def print_kwargs(latitude=None, longitude=None):
    print(latitude, longitude)

data = {'latitude': 0.00, 'longitude': 1.00}
print_data(**data)
>>> 0.00 1.00

def print_kwargs(lat=None, long=None, **kwargs):
    print(lat, long, kwargs)
print_kwargs(1, 2, data='other')
>>> 1 2 {'data': 'other'}



class Base(object):
    def __init__(self, *args, data=None, **kwargs):
        print('data is: ', data)

class MyBaseObject(Base):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

class MyObject(MyBaseObject):
    def __init__(self, *args, game=None, **kwargs):
        super().__init__(*args, **kwargs)
        print('game is: ', game)

my_data = {'game': 'UT', 'data': '3d'}
MyObject(**my_data)
>>> data is: 3d
>>> game is: UT
comments powered by Disqus