Python Tricks - Effective Functions(3)

Fun With *args and **kwargs

I once pair-programmed with a smart Pythonista who would exclaim “argh!” and “kwargh!” every time he typed out a function definition with optional or keyword parameters. We got along great otherwise. I guess that’s what programming in academia does to people eventually.

Now, while easily mocked, *args and **kwargs parameters are nevertheless a highly useful feature in Python. And understanding their potency will make you a more effective developer.

单星和双星虽然被大家嘲笑,但是是python里面很有用的语言特性。理解它们的效力会使工作更有效率。

So what are *args and **kwargs parameters used for? They allow a function to accept optional arguments, so you can create flexible APIs in your modules and classes:

def foo(required, *args, **kwargs):
  print(required)
  if args:
    print(args)
  if kwargs:
    print(kwargs)

单星和双星语法可以使得函数可以接受更加可选的参数,所以我们可以在类或者魔魁阿忠创造更加灵活地API。

The above function requires at least one argument called “required,” but it can accept extra positional and keyword arguments as well.

上面的函数至少要接受一个叫required的参数,但是它也可以接受其他的位置参数或者关键字参数。

If we call the function with additional arguments, args will collect extra positional arguments as a tuple because the parameter name has a * prefix.

如果我们用更多的参数来调用这个函数,函数可以以元组的形式采集其余的位置参数,因为参数名前面有单星前缀。

Likewise, kwargs will collect extra keyword arguments as a dictionary because the parameter name has a ** prefix.

相似得,因为有双星号前缀存在,函数会以字典的形式手机其他的关键字参数。

Both args and kwargs can be empty if no extra arguments are passed to the function.

如果没有其他的值传入,args和kwargs可以为空。

As we call the function with various combinations of arguments, you’ll see how Python collects them inside the args and kwargs parameters according to whether they’re positional or keyword arguments:

>>> foo()
TypeError:
"foo() missing 1 required positional arg: 'required'"

>>> foo('hello')
hello

>>> foo('hello', 1, 2, 3)
hello
(1, 2, 3)

>>> foo('hello', 1, 2, 3, key1='value', key2=999)
hello
(1, 2, 3)
{'key1': 'value', 'key2': 999}

python会根据是否是关键字参数还是位置参数来进行收集。

I want to make it clear that calling the parameters args and kwargs is simply a naming convention. The previous example would work just as well if you called them parms and argv. The actual syntax is just the asterisk () or double asterisk (), respectively.

这种语法表达里面最重要的是双星号和单星号,而不是星号之后的命名。

However, I recommend that you stick with the accepted naming convention to avoid confusion. (And to get a chance to yell “argh!” and “kwargh!” every once in a while.)

作者还是在这里推荐我们按照惯例走。

Forwarding Optional or Keyword Arguments

It’s possible to pass optional or keyword parameters from one function to another. You can do so by using the argument-unpacking operators * and ** when calling the function you want to forward arguments to.

This also gives you an opportunity to modify the arguments before you pass them along. Here’s an example:

def foo(x, *args, **kwargs):
  kwargs['name'] = 'Alice'
  new_args = args + ('extra', )
  bar(x, *new_args, **kwargs)

我们拥有着在传递双星和单星参数之前对参数进行修改的机会。

This technique can be useful for subclassing and writing wrapper functions. For example, you can use it to extend the behavior of a parent class without having to replicate the full signature of its constructor in the child class. This can be quite convenient if you’re working with an API that might change outside of your control:

class Car:
  def __init__(self, color, mileage):
    self.color = color
    self.mileage = mileage

class AlwaysBlueCar(Car):
  def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.color = 'blue'

>>> AlwaysBlueCar('green', 48392).color
'blue'

利用这个性能我们就可以向上面那个例子中的一样,我们不用太在意父类中初始化的参数有什么,直接一股脑扔个子类就好了。但是我们也可以用过对子类的初始化设定对一些参数进行调整,而改变子类的属性或者行为。

The AlwaysBlueCar constructor simply passes on all arguments to its parent class and then overrides an internal attribute. This means if the parent class constructor changes, there’s a good chance that AlwaysBlueCar would still function as intended.

父类发生变化,子类不变。

The downside here is that the AlwaysBlueCar constructor now has a rather unhelpful signature—we don’t know what arguments it expects without looking up the parent class.

但是有一个坏处就是我们如果不看父类又什么参数的话,不知道子类都被传递了什么。

Typically you wouldn’t use this technique with your own class hierarchies. The more likely scenario would be that you’ll want to modify or override behavior in some external class which you don’t control.

一般情况下,我们不会用这个(就是双星和单星)在我们自己的类的继承上。更可能的情景是你想去修改或者改写一些你不控制的外部类的行为

But this is always dangerous territory, so best be careful (or you might soon have yet another reason to scream “argh!”).

在使用双星或者单星语法的时候我们需要加以注意。

One more scenario where this technique is potentially helpful is writing wrapper functions such as decorators. There you typically also want to accept arbitrary arguments to be passed through to the wrapped function.

这个技术有用的一个场景是写如装饰器这样的封装函数的时候。我们可能会需要将接受任意的参数传递到被封装的函数中。

And, if we can do it without having to copy and paste the original function’s signature, that might be more maintainable:

def trace(f):
  @functools.wraps(f)
  def decorated_function(*args, **kwargs):
    print(f, args, kwargs)
    result = f(*args, **kwargs)
    print(result)
  return decorated_function

@trace
def greet(greeting, name):
  return '{}, {}!'.format(greeting, name)

>>> greet('Hello', 'Bob')
 ('Hello', 'Bob') {}
'Hello, Bob!'

我们不用复制和粘贴原始函数的签名就可以做到这一点,这样更可维护。

With techniques like this one, it’s sometimes difficult to balance the idea of making your code explicit enough and yet adhere to the Don’t Repeat Yourself (DRY) principle. This will always be a tough choice to make. If you can get a second opinion from a colleague, I’d encourage you to ask for one.

需要平衡在使得代码足够清晰和不要自己重复自己(应该是大量重复的代码)。

Key Takeaways

  • *args and **kwargs let you write functions with a variable number of arguments in Python.
  • *args collects extra positional arguments as a tuple **kwargs collects the extra keyword arguments as a dictionary.
  • The actual syntax is * and **. Calling them args and kwargs is just a convention (and one you should stick to).

你可能感兴趣的:(Python Tricks - Effective Functions(3))