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')
<function greet at 0x1031c9158> ('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).
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,542评论 6 504
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,822评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,912评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,449评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,500评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,370评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,193评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,074评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,505评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,722评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,841评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,569评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,168评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,783评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,918评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,962评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,781评论 2 354

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,325评论 0 10
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,451评论 0 13
  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom阅读 2,696评论 0 3
  • 秋天 是来了吗? 好像吧 吹了一个晚上的风 就把秋天给吹来了 那么 秋天别来可以吗 或者 可以晚一点来吗 让我再感...
    多摩呸呸呸_ian阅读 228评论 0 1
  • 最近在更新ButterKnife时发现出了点问题,到官网看了一下,原来ButterKnife使用apt.配置也要进...
    口袋易佰阅读 352评论 0 0