Let there be holivar! To use args / kwargs or not to use, is this an indicator of professionalism or basic knowledge, without which you should be ashamed? Often flipping through the github of various projects, you come across the presence of these arguments in functions simply because. And this article prompted me to talk about this topic. In general, I try not to use uncontrolled argumentation in practice, but how common is this programming method? Share in the comments. And enjoy your reading.
, *args
**kwargs
Python. , , . , .
!
. , , , .
?
Python :
, .
, .
def foo(start, end):
print(start, end)
, foo ('Hi', end = 'Bye!')
"Hi"
"Bye!"
, end
foo
. ; , , . .
*args
. *
- . .
def foo(*args):
print(type(args))
for arg in args:
print(arg)
foo(1, 2, 'end')
# <class 'tuple'>
# 1
# 2
# end
, **kwargs
. , .
def foo2(**kwargs):
print(type(kwargs))
for keyword, value in kwargs.items():
print(f'{keyword}={value}')
foo2(a=1, b=2, z='end')
# <class 'dict'>
# a=1
# b=2
# z=end
*args
**kwargs
. , ?
, , , .
, . - Python
- ?
: , . , , . , , , , , ..
, *args
/ **kwargs
, , , .
, . , , .
, Python , , , .
In the following example, we create
one that outputs the name of the function being executed as a health check. The decorator is applied to the function using @trace
on top of the function as shown below. Since we want to apply this decorator to any function 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
@trace
def calc(a,b):
print(f'a+b is {a+b}, a-b is {a-b}.')
calc(1,2)
# Executing function calc
# a+b is 3, a-b is -1.
@trace
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
conclusions
Avoid them if possible.
Note that args
and kwargs
are so called simply by agreement. You can call them whatever you want. It is the stars *
that **
give the functions that very power.