将kwargs转换为变量? [英] Converting kwargs into variables?
问题描述
如何将kwargs对象转换为局部变量?我是一名数学老师,我想编写一个辅助函数,可以在其中使用JS样式的模板字符串编写问题.
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.
我想做这样的事情:
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...'
我将在字符串中搜索"{{}}",然后在其中的内容上调用eval().但是首先我需要将{'a':3,'b':5}转换为局部变量a = 3和b = 5.变量可以是int,float或str.最好的方法是什么?
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?
推荐答案
如果您打算使用 eval
,则根本不需要将其转换为本地语言. eval
需要可选的 globals
和/或 locals
自变量,用于定义该表达式的活动范围变量.如果您提供 globals
(第二个位置参数)而不提供 locals
(第三个位置),那么 globals
将被重新用作 locals 代码>,例如:
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
这篇关于将kwargs转换为变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!