python - 缩短用于测试 Python 返回值的常用代码段

标签 python optimization

考虑这个 Python 片段:

def someTestFunction():
    if someTest:
        return value1
    elif someOtherTest:
        return value2
    elif yetSomeOtherTest:
        return value3
    return None

def SomeCallingFunction():
    a = someTestFunction()
    if a != None:
        return a

    ... normal execution continues

现在,问题是:SomeCallingFunction 开头的三行代码段用于获取测试函数的值,如果它不是 None 则退出,在许多其他函数中经常重复。三行太长了。我想把它缩短为一个。我该怎么做?

我可以根据需要自由重构此代码和 someTestFunction 的内容。我考虑过使用异常,但这些似乎对减少调用代码长度没有帮助。

(我已经阅读了一些关于 Python 装饰器的内容,但还没有使用过它们。会是这个地方吗?它是如何工作的?)

最佳答案

如果你想使用装饰器,它看起来像这样:

def testDecorator(f):
    def _testDecorator():
        a = someTestFunction()
        if a is None:
            return f()
        else: return a
    return _testDecorator

@testDecorator
def SomeCallingFunction():
    ... normal execution

首次导入模块时,它会运行 testDecorator,将您的原始 SomeCallingFunction 作为参数传递给它。返回一个新函数,并绑定(bind)到 SomeCallingFunction 名称。现在,无论何时调用 SomeCallingFunction,它都会运行另一个函数,它会进行检查,并返回 a 或原始 SomeCallingFunction 的结果>.

关于python - 缩短用于测试 Python 返回值的常用代码段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/694775/

相关文章:

python - Pandas 数据框获取扩展/滚动值计数

sql - udf 与直接 sql 性能

java - 针对重量而不是值优化的背包算法

optimization - 通用 Lisp : Optimizing file parsing for minimum reads and memory allocations

optimization - 范围编码器 : How to get rid of divisions?

python - 在类中编写一个函数来生成给定范围内的六个随机数的列表

python - 理解和测试 [self._class_._module_]._file_

python - 用字典更改列表中的项目

python - 基于连续点简化元组列表

r - 当数据在列表中时,我可以向量化代码吗?