python - 嵌套函数返回外部函数
问题描述
我有一个共同的模式,就像
def f(x):
if x.type == 'Failure':
# return `x` immediately without doing work
return x
else:
# do stuff with x...
return x
我想将if/else模式抽象为一个独立的函数。但是,我希望该函数在从内部调用时f
立即从 f 返回。否则它应该只将 x 返回到f 内的值以进行进一步处理。就像是
def g(x):
if x.type == 'Failure':
global return x
else:
return x.value
def f(x):
x_prime = g(x) # will return from f
# if x.type == 'Failure'
# do some processing...
return x_prime
这在 Python 中可能吗?
解决方案
我正在使用Validation
我的pycategories 分支:
def fromSuccess(fn):
"""
Decorator function. If the decorated function
receives Success as input, it uses its value.
However if it receives Failure, it returns
the Failure without any processing.
Arguments:
fn :: Function
Returns:
Function
"""
def wrapped(*args, **kwargs):
d = kwargs.pop('d')
if d.type == 'Failure':
return d
else:
kwargs['d'] = d.value
return fn(*args, **kwargs)
return wrapped
@fromSuccess
def return_if_failure(d):
return d * 10
return_if_failure(d = Failure(2)), return_if_failure(d = Success(2))
>>> (Failure(2), 20)
推荐阅读
- swift - 为什么在插入大字符串数据时 NSScrollView 冻结应用程序
- c++ - 带有模板的 C++ 事件系统 - 如何存储采用任意类型的订阅者函数?
- magento2 - Magento 2 REST 搜索从 Order_ID 开始的订单
- c++ - 取消引用指向整数的指针时得到不同的结果
- python-3.x - 从熊猫数据框中删除 \n 的问题
- nestjs - 使用 CLI 和 NestJS 应用程序的一种配置配置 TypeORM
- c# - 在 AutoMapper ForMember 映射中重用代码
- php - IF 条件内部的代码应该运行还是只评估?
- java - 如何通过读取 JSON 来修复 UnrecognizedPropertyException?
- linux - 加载核心文件时,gdb 不会加载共享库符号,甚至 libc.so (musl)