Python在lambda中尝试Catch Block

scr*_*ddy 38 python lambda try-catch

是否可以在lambda函数中使用try catch块.我需要lambda函数将某个变量转换为整数,但并非所有的值都能转换为整数.

kin*_*all 60

不.Python lambda只能是单个表达式.使用命名函数.

编写用于转换类型的通用函数很方便:

def tryconvert(value, default, *types):
    for t in types:
        try:
            return t(value)
        except (ValueError, TypeError):
            continue
    return default
Run Code Online (Sandbox Code Playgroud)

然后你可以写你的lambda:

lambda v: tryconvert(v, 0, int)
Run Code Online (Sandbox Code Playgroud)

你也可以写,tryconvert()所以它返回一个函数,它接受转换的值; 那么你不需要lambda:

def tryconvert(default, *types):
    def convert(value):
        for t in types:
            try:
                return t(value)
            except (ValueError, TypeError):
                continue
        return default
    # set name of conversion function to something more useful
    namext = ("_%s_" % default) + "_".join(t.__name__ for t in types)
    if hasattr(convert, "__qualname__"): convert.__qualname__ += namext
    convert.__name__ += namext
    return convert
Run Code Online (Sandbox Code Playgroud)

现在tryconvert(0, int)返回一个取值的函数并将其转换为整数,0如果无法完成则返回.


Gre*_*ill 26

在此特定实例中,您可以避免使用这样的try块:

lambda s: int(s) if s.isdigit() else 0
Run Code Online (Sandbox Code Playgroud)

isdigit()字符串的方法,如果返回true,所有的字符s是数字.(如果你需要接受负数,你将不得不做一些额外的检查.)

  • 它要求将某个值转换为整数。这并没有指定这个值是否必须是一个整数才有效。此外,这个特定值甚至*不必*是一个字符串。尽管如此,了解它仍然是有用的。 (3认同)

kyr*_*ill 5

对的,这是可能的

我将这段小代码放在一起,以演示在 lambda 中捕获异常并对其做出反应的可能性。它相当初级,或多或少地用作概念证明。

例子

>>> print_msg = lambda msg, **print_kwargs: \
...   begin(
...     print, msg, end='... ', **print_kwargs
...   ).\
...   rescue(
...     (TypeError, AttributeError),
...     lambda exc: print(f'just caught "{exc}"! how fun!')
...   ).\
...   ensure(print, 'ok done.')()

>>> print_msg('check')
check... ok done.

>>> print_msg('check', file=1)
just caught "'int' object has no attribute 'write'"! how fun!
ok done.

>>> print_msg('check', sep=1)
just caught "sep must be None or a string, not int"! how fun!
ok done.
Run Code Online (Sandbox Code Playgroud)

一个更实际的例子

modules = filter(None, (
  begin(importlib.import_module, modname).rescue(lambda exc: None)()
  for modname in module_names
))
Run Code Online (Sandbox Code Playgroud)


代码

modules = filter(None, (
  begin(importlib.import_module, modname).rescue(lambda exc: None)()
  for modname in module_names
))
Run Code Online (Sandbox Code Playgroud)