Home  >  Article  >  Backend Development  >  Function parameter passing methods in Python *args, **kwargs, and others

Function parameter passing methods in Python *args, **kwargs, and others

PHPz
PHPzforward
2023-04-13 09:58:151860browse

This article will discuss Python’s function parameters. We will learn about args and **kwargs, what / and are. Although this question is a basic python question, it will often be encountered when we write code. For example, it is widely used in timm. This way of passing parameters.

Function parameter passing methods in Python *args, **kwargs, and others

Defining and passing parameters

What is the difference between parameters and arguments?

Many people use these terms interchangeably, but they There is a difference:

  • Parameters are the names defined in the function definition
  • Arguments are the values ​​passed to the function

Function parameter passing methods in Python *args, **kwargs, and others

The red ones are parameters and the green ones are arguments.

Two ways to pass parameters

We can pass parameters by position and keyword. In the following example, we pass the value hello as a positional parameter. The value world is passed using the keyword.

 def the_func(greeting, thing):
 print(greeting + ' ' + thing)
 
 the_func('hello', thing='world')

The difference between positional parameters and kwargs (keyword parameters) is that the order in which positional parameters are passed matters. If you call the_func('world', 'hello') it will print world hello. The order in which the kwargs are passed does not matter:

the_func('hello', 'world')# -> 'hello world'
the_func('world', 'hello')# -> 'world hello'
the_func(greeting='hello', thing='world') # -> 'hello world'
the_func(thing='world', greeting='hello') # -> 'hello world'
the_func('hello', thing='world')# -> 'hello world'

As long as the kwarg comes after the positional parameters, you can mix and match positional and keyword arguments. The above is what we often see in python tutorials. content, let’s continue below.

Function parameters

We will demonstrate 6 methods of passing function parameters, which can cover all problems.

1. How to get all uncaught positional parameters

Use *args to let it receive an unspecified number of formal parameters.

def multiply(a, b, args):
result = a * b
for arg in args:
result = result * arg
return result

In this function, we usually define the first two parameters (a and b). Then use args to pack all remaining arguments into a tuple. You can think of * as getting other unprocessed parameters and collecting them into a tuple variable named "args":

multiply(1, 2)# returns 2
multiply(1, 2, 3, 4)# returns 24

The last call will have the value 1 Assign to parameter a, assign 2 to parameter b, and fill the arg variable with (3,4). Since this is a tuple, we can loop over it in the function and use the values ​​for multiplication!

2. How to get all uncaught keyword arguments

Similar to *args, this followed by two asterisks **kwargs

def introduce(firstname, lastname, **kwargs):
introduction = f"I am {firstname} {lastname}"
for key, value in kwargs.items():
introduction += f" my {key} is {value} "
return introduction

The **kwargs keyword will store all unmatched keyword arguments in a dictionary called kwargs. This dictionary can then be accessed like the function above.

 print(introduce(firstname='mike', lastname='huls'))
 # returns "I am mike huls"
 
 print(introduce(firstname='mike', lastname='huls', age=33, website='mikehuls.com'))
 # I am mike huls my age is 33 my website is overfit.cn

3. If you want to accept only keyword parameters, how to design

can force the function to only accept keyword parameters.

 def transfer_money(*, from_account:str, to_account:str, amount:int):
 print(f'Transfering ${amount} FORM {from_account} to {to_account}')
 
 transfer_money(from_account='1234', to_account='6578', amount=9999)
 # won't work: TypeError: transfer_money() takes 0 positional arguments but 1 positional argument (and 2 keyword-only arguments) were given
 transfer_money('1234', to_account='6578', amount=9999)
 # won't work: TypeError: transfer_money() takes 0 positional arguments but 3 were given
 transfer_money('1234', '6578', 9999)

In the above function, the * asterisk gets all the unmatched positional parameters, but there is no variable to accept it, that is, it is ignored.

4. How to design a function that only accepts positional parameters

The following is an example of a function that only allows positional parameters:

 def the_func(arg1:str, arg2:str, /):
 print(f'provided {arg1=}, {arg2=}')
 
 # These work:
 the_func('num1', 'num2')
 the_func('num2', 'num1')
 
 # won't work: TypeError: the_func() got some positional-only arguments passed as keyword arguments: 'arg1, arg2'
 the_func(arg1='num1', arg2='num2')
 # won't work: TypeError: the_func() got some positional-only arguments passed as keyword arguments: 'arg2'
 the_func('num1', arg2='num2')

/ in the function definition forces everything before it The parameters are all positional parameters. This does not mean that all arguments following / must be kwarg-only; these can be positional and keywords.

When you see this, you will definitely think, why do you want this? Won’t this reduce the readability of the code? I also think you are very right. When defining a very clear function, no Keyword arguments are required to specify its functionality. For example:

def exceeds_100_bytes(x, /) -> bool:
 return x.__sizeof__() > 100
 
 exceeds_100_bytes('a')
 exceeds_100_bytes({'a'})

In this example, it is checking whether the memory size of 'a' exceeds 100 bytes. Because the name of this x is not important to us, there is no need to specify x='a' when calling the function. For example, our most commonly used len, if you call len(__obj=[]), does it look a bit silly, because len is defined like this def len(__obj: Sized) -> int:

5. Mixing and matching

As an example, we will look at the len function discussed earlier. This function only allows positional arguments. We will extend this function by allowing developers to choose whether to count duplicates, such as passing this keyword with kwargs:

 def len_new(x, /, *, no_duplicates=False):
 if (no_duplicates):
 return len(list(set([a for a in x])))
 return len(x)

If you want to calculate the len of a variable x, you can only pass the parameter because it is preceded by a /. The no_duplicate parameter must be passed with the keyword since it follows . Let's see how this function can be called:

print(len_new('aabbcc'))# returns 6
 print(len_new('aabbcc', no_duplicates=True))# returns 3
 print(len_new([1, 1, 2, 2, 3, 3], no_duplicates=False)) # returns 6
 print(len_new([1, 1, 2, 2, 3, 3], no_duplicates=True))# returns 3
 
 # Won't work: TypeError: len_() got some positional-only arguments passed as keyword arguments: 'x'
 print(len_new(x=[1, 1, 2, 2, 3, 3]))
 # Won't work: TypeError: len_new() takes 1 positional argument but 2 were given
 print(len_new([1, 1, 2, 2, 3, 3], True))

6. Finally put them together

The following function is a very extreme example of how to combine all the previously discussed Technique: It forces the first two parameters to be passed positionally, the next two parameters can be passed positionally and with keywords, then the two keyword-only parameters, and then we capture the rest with **kwargs The uncaught parameter.

 def the_func(pos_only1, pos_only2, /, pos_or_kw1, pos_or_kw2, *, kw1, kw2, **extra_kw):
 # cannot be passed kwarg <-- | --> can be passed 2 ways | --> can only be passed by kwarg
 print(f"{pos_only1=}, {pos_only2=}, {pos_or_kw1=}, {pos_or_kw2=}, {kw1=}, {kw2=}, {extra_kw=}")

The calling method is as follows:

# works (pos_or_kw1 & pow_or_k2 can be passed positionally and by kwarg)
 pos_only1='pos1', pos_only2='pos2', pos_or_kw1='pk1', pos_or_kw2='pk2', kw1='kw1', kw2='kw2', extra_kw={}
 pos_only1='pos1', pos_only2='pos2', pos_or_kw1='pk1', pos_or_kw2='pk2', kw1='kw1', kw2='kw2', extra_kw={}
 pos_only1='pos1', pos_only2='pos2', pos_or_kw1='pk1', pos_or_kw2='pk2', kw1='kw1', kw2='kw2', extra_kw={'kw_extra1': 'extra_kw1'}
 
 # doesnt work, (pos1 and pos2 cannot be passed with kwarg)
 # the_func(pos_only1='pos1', pos_only2='pos2', pos_or_kw1='pk1', pos_or_kw2='pk2', kw1='kw1', kw2='kw2')
 
 # doesnt work, (kw1 and kw2 cannot be passed positionally)
 # the_func('pos1', 'pos2', 'pk1', 'pk2', 'kw1', 'kw2')

Summary

It looks messy, right? That’s right. Because Python is a very loose language when it is designed, there are not so many specifications. The more people use it, the more methods it uses, and it becomes like this.

So back to the first picture:

def func(x,/,y,,z,**k):

(x,/,y,,z,**k):是函数的参数。总共有四个参数:

  • x: 是一个常规参数,这意味着它可以按位置传递,也可以按关键字传递。
  • /,: 是一个参数分隔符,将仅限位置的参数与其他参数分开。与前面的x结合,意味着x只能按位置传递。
  • y: 时另一个常规参数。
  • *: 是一个参数分隔符,用于分隔仅限位置参数和仅限关键字参数。它意味着后面的z只能通过关键字传递。
  • z: 是一个仅限关键字的参数。
  • **k: 这是一个参数,将所有剩余的关键字参数收集到一个名为' k '的字典中。

这样解释是不是就很明白了。

我们今天介绍的这个例子虽然在看源代码时没有遇到这么复杂的情况,但是在 面试 的时候还真有人问(虽然我觉得没啥用),所以最好还是知道一些,以免尴尬。

如果你忘记了,这里可以教你一个变通的办法,可以使用类似的回答:

上面的参数传递在开发时并不常用,因为对于开发规范来说,应该保证代码的可读性,我们这边遵循的开发规范是:

1、尽量不要在函数定义中将可变位置参数 *args 和可变关键字参数 **kwargs 放在一起,因为这样会让函数的调用方式变得不太直观。

2、在使用可变参数时,要保证函数的行为是可预测的。上面函数中的进行了太多的python语法糖,对于理解该函数的参数会造成很大的困惑,也就是可读性太差,我们在进行codereview(如果你了解什么是codereview就说,不了解就说组长检查)/组长merge代码 时会直接要求返工,所以我们在实际开发时是不会用这个的。

对于我阅读的开源代码,也都基本上使用的是 **kwargs这种情况(这里可以举两个例子),还没有看到有人写这么乱的代码,我想要是写这样的代码估计开源的人也会被人吐糟(这里自己可以自行延伸),所以这些参数传递的规则我在学习的时候看到过,但是实际中没见过真正使用,就不太记住了。

回到本文,我们介绍了设计函数参数的所有方法,并了解了如何混合和匹配它们,虽然后面几个内容可能你一辈子也不会用到,但是了解一下也是好的,因为万一呢。

The above is the detailed content of Function parameter passing methods in Python *args, **kwargs, and others. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:51cto.com. If there is any infringement, please contact admin@php.cn delete