The good, the bad and the ugly is a famous western. In Python, “the ugly” is probably the **kwargs, as far as it has two stars before it. Anyhow, the idea of *args, **kwargs and arg is simply to pass arguments.
- Arg (or the normal ones) are the standard arguments in python. You declare one, you pass one, you get one.
- *Args are a bit fancier – you declare just 1 in the function with one star on the left and you pass as many as you want. From 1 to unlimited.
- **Kwargs are for named arguments. You may pass as many as you want as well.
Kwargs example
The code below takes 3 named arguments and returns both the keys and the values. On a new line, due to the “magic” of the list comprehension:
1 2 3 |
def kwargs_example(**kwargs): return "\n".join([f"{v} -> {k}" for k,v in kwargs.items()]) print(kwargs_example(Sofia="Bulgaria", Madrid="Spain", Lisbon = "Portugal")) |
1 2 3 |
Bulgaria -> Sofia Spain -> Madrid Portugal -> Lisbon |
Args example
The args are unlimited. And as this is python, these could be of any type. What if we have nothing better to do, but to pass both numbers and strings as args* to a function, which has the task to split those into strings and numbers. The numbers are to be summed together and the strings are to be united? Well, here is how it looks like:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
def args_example(*some_random_name): result_numeric = 0 result_letters = "" for arg in some_random_name: if isinstance(arg, int): result_numeric += float(arg) else: result_letters += str(arg) + " " return f'{str(result_numeric)} is number.\nAnd "{result_letters}"is a string.' print(args_example("Joe", -1, "was", 20, "here", 15, "yesterday!")) |
1 2 |
34.0 is number. And "Joe was here yesterday! "is a string. |
Arg, *Args and **Kwargs together
I really wish to think that the above will never exist in production code. Ever. However, just for learning purposes, this is how to put all 3 types in a single function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
def all_stars(arg, *args,**kwargs): result = [] #arg: result.append(arg) #*args: for arg in args: result.append(arg) #**kwargs: for key, value in kwargs.items(): result.append(value) return result print(all_stars("Joe", "Banana", "was here!", first="Somehow", last="it was fun!")) |
1 |
['Joe', 'Banana', 'was here!', 'Somehow', 'it was fun!'] |
Enjoy it! 🙂