不要那样做,在大多数情况下,中间 dict 是可以的。
可读性很重要。
如果你真的发现自己在这种情况下太频繁了,你可以使用装饰器来猴子补丁你的函数:
In : from functools import wraps
In : def dictgetter(func, *keys):
.....: @wraps(func)
.....: def wrapper(*args, **kwargs):
.....: tmp = func(*args, **kwargs)
.....: return [tmp[key] for key in keys]
.....: return wrapper
In : def func():
....: return dict(one=1, two=2, three=3)
....:
In : func2 = dictgetter(func, 'one', 'three')
In : one, three = func2()
In : one
Out : 1
In : three
Out : 3
或类似的东西。
当然,您也可以使用monkeypatch,以便在调用时指定所需的字段,但我猜您会想要一个包含这些机制的普通函数。
这将与上面的 def wrapper 的主体非常相似地实现,并像
一样使用
one, three = getfromdict(func(), 'one', 'three' )
或类似的东西,但你也可以重复使用上面的整个装饰器:
In : two, three = dictgetter(func, 'two', 'three')()
In : two, three
Out : (2, 3)