从另一个函数名称计算一个函数名称 [英] Computing a function name from another function name

查看:52
本文介绍了从另一个函数名称计算一个函数名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python 3.4中,我希望能够做一个非常简单的调度表以进行测试.想法是要有一个字典,其中的键是要测试的功能名称的字符串,而数据项是测试功能的名称.

In python 3.4, I want to be able to do a very simple dispatch table for testing purposes. The idea is to have a dictionary with the key being a string of the name of the function to be tested and the data item being the name of the test function.

例如:

myTestList = (
    "myDrawFromTo",
    "myDrawLineDir"
)

myTestDict = {
    "myDrawFromTo": test_myDrawFromTo,
    "myDrawLineDir": test_myDrawLineDir
}

for myTest in myTestList:
    result = myTestDict[myTest]()

这个想法是我有某个地方的函数名列表.在此示例中,我手动创建了一个字典,将这些名称映射到测试函数的名称.测试功能名称是功能名称的简单扩展.我想从函数名称列表中计算整个字典(这里是 myTestList ).

The idea is that I have a list of function names someplace. In this example, I manually create a dictionary that maps those names to the names of test functions. The test function names are a simple extension of the function name. I'd like to compute the entire dictionary from the list of function names (here it is myTestList).

或者,如果我不用字典也可以做同样的事情,那也很好.我尝试仅从myTestList中的条目构建一个新字符串,然后使用 local()设置该调用,但是没有任何运气.字典的想法来自 Python 3.x文档.

Alternately, if I can do the same thing without the dictionary, that'd be fine, too. I tried just building a new string from the entries in myTestList and then using local() to set up the call, but didn't have any luck. The dictionary idea came from the Python 3.x documentation.

推荐答案

问题有两个部分.

最简单的部分是在每个字符串的前面加上'text _':

The easy part is just prefixing 'text_' onto each string:

tests = {test: 'test_'+test for test in myTestDict}

更难的部分实际上是按名称查找功能.这类事情通常不是一个好主意,但是您碰到了其中一种情况(生成测试)通常很有意义的情况.您可以通过在您模块的全局词典中查找它们来进行操作,例如这个:

The harder part is actually looking up the functions by name. That kind of thing is usually a bad idea, but you've hit on one of the cases (generating tests) where it often makes sense. You can do this by looking them up in your module's global dictionary, like this:

tests = {test: globals()['test_'+test] for test in myTestList}


如果测试存在于模块的全局范围之外的其他地方,则在相同的想法上会有不同之处.例如,使它们成为类的所有方法可能是一个好主意,在这种情况下,您可以这样做:


There are variations on the same idea if the tests live somewhere other than the module's global scope. For example, it might be a good idea to make them all methods of a class, in which case you'd do:

tester = TestClass()
tests = {test: getattr(tester, 'test_'+test) for test in myTestList}

(尽管代码很有可能位于 TestClass 内部,所以它将使用 self 而不是 tester .)

(Although more likely that code would be inside TestClass, so it would be using self rather than tester.)

当然,如果您实际上不需要该字典,则可以将理解更改为显式的 for 语句:

If you don't actually need the dict, of course, you can change the comprehension to an explicit for statement:

for test in myTestList:
    globals()['test_'+test]()


另一件事:在重新发明轮子之前,您是否已查看内置于其中的stdlib ,或在PyPI上可用?

这篇关于从另一个函数名称计算一个函数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆