1

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'))
1
  • Does this boltons.iterutils.remap thing have additional parameters to pass to the callback? Commented May 10, 2017 at 16:22

1 Answer 1

1

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')))
Sign up to request clarification or add additional context in comments.

2 Comments

Great idea. I'm still learning when to apply lambda functions, so it didn't occur to me.
You could do the same thing wtih a regular function def foo(key, value): return visit(key, value, lang='ru') - this is just one of those times when a lambda fits and you don't have to think of a function name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.