Search code examples
pythonkeyword-argument

Why use **kwargs in python? What are some real world advantages over using named arguments?


I come from a background in static languages. Can someone explain (ideally through example) the real world advantages of using **kwargs over named arguments?

To me it only seems to make the function call more ambiguous. Thanks.


Solution

  • Real-world examples:

    Decorators - they're usually generic, so you can't specify the arguments upfront:

    def decorator(old):
        def new(*args, **kwargs):
            # ...
            return old(*args, **kwargs)
        return new
    

    Places where you want to do magic with an unknown number of keyword arguments. Django's ORM does that, e.g.:

    Model.objects.filter(foo__lt = 4, bar__iexact = 'bar')