Nicholas Tulach
Nicholas Tulach

Reputation: 1083

How to pass additional parameters to python callback?

I have the following sample block of code, where i'm trying to translate text from one language to another. I need to be able to pass in an additional argument that represents which target language i want to translate into.

How do i add another argument to the list of arguments from the callback in boltons.iterutils.remap?

I thought maybe using the **kwargs in the remap call would work, but it doesn't. It raises a TypeError:

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

Any help would be greatly appreciated.

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'))

Upvotes: 1

Views: 176

Answers (1)

tdelaney
tdelaney

Reputation: 77337

Apparently boltons.iterutils.remap doesn't pass additional keyword parameters to its callback - and one really wouldn't expect it to. So, you can't call visit directly. You can, however, call a different function that fills in the value for you. This is a good use-case for 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')))

Upvotes: 1

Related Questions