如何将其他参数传递给python回调?

时间:2017-05-10 16:07:47

标签: python python-3.x

我有以下示例代码块,我正在尝试将文本从一种语言翻译成另一种语言。我需要能够传入一个额外的参数来表示我想要翻译成哪种目标语言。

如何在boltons.iterutils.remap

的回调中添加另一个参数列表

我认为使用**kwargs调用中的remap可能有效,但事实并非如此。它引发了一个TypeError:

raise TypeError('unexpected keyword arguments: %r' % kwargs.keys())

非常感谢任何帮助。

import json
from boltons.iterutils import remap

def visit(path, key, value, lang='es'):
    if value is None or value == '' or not isinstance(value, str):
        return key, value
    return key, '{}:{}'.format(lang, value)

if __name__ == '__main__':
    test_dict = { 'a': 'This is text', 'b': { 'c': 'This is more text', 'd': 'Another string' }, 'e': [ 'String A', 'String B', 'String C' ], 'f': 13, 'g': True, 'h': 34.4}
    print(remap(test_dict, visit=visit, lang='ru'))

1 个答案:

答案 0 :(得分:1)

显然boltons.iterutils.remap没有将额外的关键字参数传递给它的回调 - 而且人们真的不希望这样做。因此,您无法直接致电visit。但是,您可以调用另一个为您填写值的函数。这是lambda的一个很好的用例。

import json
from boltons.iterutils import remap

def visit(path, key, value, lang='es'):
    if value is None or value == '' or not isinstance(value, str):
        return key, value
    return key, '{}:{}'.format(lang, value)

if __name__ == '__main__':
    test_dict = { 'a': 'This is text', 'b': { 'c': 'This is more text', 'd': 'Another string' }, 'e': [ 'String A', 'String B', 'String C' ], 'f': 13, 'g': True, 'h': 34.4}
    print(remap(test_dict, visit=lambda key, value: visit(key, value, lang='ru')))
相关问题