0

How do I convert kwargs objects into local variables? I am a math teacher and I want to write a helper function where I can use JS-style template strings to write problems.

I want to do something like this:

TemplateString('{{a*b}} apples are shared among {{a}} children. How many apples do each child get?', {'a': 3, 'b': 5})
//return '15 apples are shared among 3 children...'

I am going to search for '{{}}' in strings and call eval() on what is inside that. But first I need to convert {'a': 3, 'b': 5} into local variables a=3 and b=5. The variables could be int, float or str. What is the best way to do this?

user2341726
  • 294
  • 1
  • 9
  • Is your dictionary always have 2 elements, `a` and `b`? If so, just simply do `int(dict['a'])*int(dict['b'])`. Is that what you want? – Huy Vo Mar 10 '17 at 05:16

1 Answers1

2

If you're planning to use eval, you don't need to convert them to locals at all. eval takes optional globals and/or locals arguments that defines the active scope variables for that expression. If you provide globals (the second positional argument) and not locals (the third), then globals is reused as locals, so for example:

>>> eval('a * b', {'a': 5, 'b': 3})
15
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271