Today, in Python explained, we are welcome to see one of the most mysterious things with a new Python learner. It is *args
and **kwargs
variables. We will figure out below questions:
- What is
*args
and**kwargs
variables? - When SHOULD and SHOULD NOT use
*args
and**kwargs
- The
*
and**
(asterisk) operators in*arg
and**kwargs
By answering questions, we step by step to understand these two special variables. And I strongly believe that you will be confident to use it in your next project.
What is *arg
?
*args
represents for arguments , it means we can pass many arguments to a function within only one variable *args
. *args
will be parsed as a list of arguments and store in args
variable.
This variable is especially useful when you define a function but not sure how many arguments you will receive. Take a look example below to get clear *args
def arg_func(*args):
for arg in args:
print(arg)
arg_func("Yellow")
# Yellow
arg_func("Yellow", "Green", "Black")
# Yellow
# Green
# Black
As you can see by running the example, no matter the number of argument was passed, the function still run expectedly. So remember this handy syntax and use it effectively.
What is **kwarg
?
**kwargs
represents for keyword arguments. It means the function will allow us to pass many keyword variables a time. Therefore, the input **kwargs
will be parsed as a dictionary instead of a list such as *args
.
This variable also useful when you don’t know how many keywords you should define in function. Or there is a large number of keyword variables that will be passed to function.
The example below will show you how to use **kwarg
:
def kwarg_func(**kwargs):
for key, value in kwargs.items():
print("Key: {}. Value: {}".format(key, value))
kwarg_func(name="Yasuo")
# Key: name. Value: Yasuo
kwarg_func(name="Yasuo", age=21, city="SG")
# Key: name. Value: Yasuo
# Key: age. Value: 21
# Key: city. Value: SG
When SHOULD and SHOULD NOT use *args
and `kwargs` **
Want to create a flexible function
Take advantage of *args
and **kwargs
will help you create a flexible function. You don’t have to define the number of arguments and its name as usual.
A Large number of arguments
It will be fine if our function has 2 or 3 arguments such as def new_func(name, age)
. However, if there are 20 arguments to be defined in a function such as def new_func(name, age, city, provine, phone, experiences, major, university,...)
, this time we should use *arg
and **kwargs
to shorten it.
Be aware when using *args
and **kwargs
Nobody can’t refuse *arg
and **kwargs
useful, but it cost you the readability. Obviously, when reading code, the function like def new_func(name, age)
will easier to understand that def new_func(*args)
.
Furthermore, when coding the body of a function, it is easy to get an unexpected error if calling or using the variable that not exists in the **kwargs
.
*arg
and **kwargs
have its own cons and pros, so be aware when using it. Don’t overuse of it and have to trade by your code quality.
The *
and **
(asterisk) operator in *arg
and **kwargs
Some of the beginners think about it as a special mark that Python uses to recognize special variables like *arg
and **kwargs
. Actually, *
and **
are the unpacking operator that help you. In short, it unpacked the values from iterable in Python.
Example of *
:
>>> A = [1, 2, 3]
>>> print(*A)
1 2 3
Example of **
:
>>> B = {"name": "Yasuo", "age": 29}
>>> C = {"city": "SG"}
>>> {**B, **C}
{'name': 'Yasuo', 'age': 29, 'city': 'SG'}
We can use *
with a string
:
>>> [*"Python Geeks"]
['P', 'y', 't', 'h', 'o', 'n', ' ', 'G', 'e', 'e', 'k', 's']
Conclusion
You now fully understand and ready to use *arg
and **kwargs
in your next project. Just keep in mind that there is no perfect solution, we want useful stuff, it can cost us readability. Be aware and use it effectively based on your real situation.
We would take a look at what we have been walking through:
- What is
*args
and**kwargs
variables? - When SHOULD and SHOULD NOT use
*args
and**kwargs
- The
*
and**
(asterisk) operators in*arg
and**kwargs
As a beginner, we recommend you other useful posts at Python Geeks:
The post Python *args & **kwargs in depth appeared first on Python Geeks.
Top comments (0)