Notes when Use *args and **kwargs to defining function in Python

Notes when Use *args and **kwargs to defining function in Python

There are many tutorials online that aim to teach you how to use *args and **kwargs when defining a function in Python. But, stop Abusing *args and **kwargs in Python

There are many tutorials online that aim to teach you how to use *args and **kwargs when defining a function in Python. Perhaps you’ve already spent hours trying to figure out how you could unleash their potential. Maybe, after all that study, you now feel confident about them.


Powerful tools are dangerous. You may have made your day easier but mark my words, it will come back and haunt you later.

But why?

Some Basics

Parameters in a Python function can accept two types of arguments:

  • Positional arguments that are passed positionally.
  • Keyworded arguments that are supplied by keywords.
def foo(start, end):
    print(start, end)

For example, foo('Hi', end='Bye!') feeds a positional argument, 'Hi', and a keyword argument 'Bye!' with keyword end to function foo. Parameters of a function are pre-defined; the number of parameters accepted in a function is fixed. However, that’s not always the case.

*args allows you to pass an arbitrary number of positional arguments to your function. The asterisk * is an unpacking parameter. They are packed as an iterable tuple inside the function.

def foo(*args):
    for arg in args:
foo(1, 2, 'end')

# <class 'tuple'>
# 1
# 2
# end

On the other hand, **kwargs allows you to pass a varying number of keyworded arguments to your function. Since each keyworded argument has a keyword and a value, it’s grouped as an iterable dictionary inside the function.

def foo2(**kwargs):
    for keyword, value in kwargs.items():
foo2(a=1, b=2, z='end')

# <class 'dict'>
# a=1
# b=2
# z=end
The Problem

You do not really need *args and **kwargs in most cases. How often do you not know how many arguments a pre-defined function should receive?

Code is much harder to debug if you abuse them because you’re letting an arbitrary number of arguments be passed to the function, and the function might have unpredictable behaviour.

When to Use It?

In short: Use them when you really need them. For instance, a function with a lot of optional fields and some of them are used only in some situations. Say, a function plots a graph and you can pass various optional arguments to modify its colour, style, size etc.

Every time you use *args and/or **kwargs, make sure you make very clear documentation to avoid confusion.

There is one scenario where their use might be inevitable. If you’re creating a wrapper for a function with unknown arguments, you would then have to accept an arbitrary number of positional and keyword arguments, then pass them to the function.

For example, decorators in Python work as wrappers that change the behaviour of the code, without changing the function code itself, thus augmenting extra functionalities.

In the following example, we build trace that prints out the name of the executing function as a sanity check. The decorator is applied to a function using @trace on top of the function, as shown below. Since we want to apply this decorator to any functions with any number of arguments, we need to use *args and **kwargs.

def trace(func):
    def print_in(*args, **kwargs):
        print('Executing function', func.__name__)
        return func(*args, **kwargs)
    return print_in
def calc(a,b):
    print(f'a+b is {a+b}, a-b is {a-b}.')  

# Executing function calc
# a+b is 3, a-b is -1.

def add_all(*args):
    print(reduce(lambda a,b:a+b, args))

a = add_all(1,2,3,4,5)
# Executing function add_all
# 15

Avoid them if possible.

Note that args and kwargs are just named by convention. You can name them whatever you like. It is the asterisks * and ** that make them powerful.

Thanks for reading! If you’re interested in improving your Python skills further, please share it with others who may enjoy it as well.!

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

What’s new in HTML6

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Guide to Python Programming Language

Guide to Python Programming Language

Guide to Python Programming Language

The course will lead you from beginning level to advance in Python Programming Language. You do not need any prior knowledge on Python or any programming language or even programming to join the course and become an expert on the topic.

The course is begin continuously developing by adding lectures regularly.

Please see the Promo and free sample video to get to know more.

Hope you will enjoy it.

Basic knowledge
An Enthusiast Mind
A Computer
Basic Knowledge To Use Computer
Internet Connection
What will you learn
Will Be Expert On Python Programming Language
Build Application On Python Programming Language

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Hello and welcome to brand new series of wiredwiki. In this series i will teach you guys all you need to know about python. This series is designed for beginners but that doesn't means that i will not talk about the advanced stuff as well.

As you may all know by now that my approach of teaching is very simple and straightforward.In this series i will be talking about the all the things you need to know to jump start you python programming skills. This series is designed for noobs who are totally new to programming, so if you don't know any thing about

programming than this is the way to go guys Here is the links to all the videos that i will upload in this whole series.

In this video i will talk about all the basic introduction you need to know about python, which python version to choose, how to install python, how to get around with the interface, how to code your first program. Than we will talk about operators, expressions, numbers, strings, boo leans, lists, dictionaries, tuples and than inputs in python. With

Lots of exercises and more fun stuff, let's get started.

Download free Exercise files.


Who is the target audience?

First time Python programmers
Students and Teachers
IT pros who want to learn to code
Aspiring data scientists who want to add Python to their tool arsenal
Basic knowledge
Students should be comfortable working in the PC or Mac operating system
What will you learn
know basic programming concept and skill
build 6 text-based application using python
be able to learn other programming languages
be able to build sophisticated system using python in the future

To know more:

Learn Python Programming

Learn Python Programming

Learn Python Programming

Learn Python Programming

Learn Python Programming and increase your python programming skills with Coder Kovid.

Python is the highest growing programming language in this era. You can use Python to do everything like, web development, software development, cognitive development, machine learning, artificial intelligence, etc. You should learn python programming and increase your skills of programming.

In this course of learn python programming you don't need any prior programming knowledge. Every beginner can start with.

Basic knowledge
No prior knowledge needed to learn this course
What will you learn
Write Basic Syntax of Python Programming
Create Basic Real World Application
Program in a fluent manner
Get Familiar in Programming Environment