我怎么能写一个相当于的lambda表达式:
def x():
raise Exception()
Run Code Online (Sandbox Code Playgroud)
以下是不允许的:
y = lambda : raise Exception()
Run Code Online (Sandbox Code Playgroud) 首先,我不确定我的方法是否合适,所以我愿意接受各种建议.
如果在代码中经常重复try/except语句,有没有什么好方法可以缩短它们或避免完全写出来?
try:
# Do similar thing
os.remove('/my/file')
except OSError, e:
# Same exception handing
pass
try:
# Do similar thing
os.chmod('/other/file', 0700)
except OSError, e:
#Same exception handling
pass
Run Code Online (Sandbox Code Playgroud)
例如,对于一行操作,您可以定义异常处理包装器,然后传递lambda函数:
def may_exist(func):
"Work with file which you are not sure if exists."""
try:
func()
except OSError, e:
# Same exception handling
pass
may_exist(lambda: os.remove('/my/file'))
may_exist(lambda: os.chmod('/other/file', 0700))
Run Code Online (Sandbox Code Playgroud)
这种"解决方案"是否会让事情变得不那么明确?我应该完全写出所有的try/except语句吗?
如何在 lambda 中使用上下文管理器?接受黑客攻击。暂缓认为这是 lambda 的错误用法的观点。
我知道我可以这样做:
def f():
with context():
return "Foo"
Run Code Online (Sandbox Code Playgroud)
但我想做这样的事情:
lambda: with context(): "Foo"
Run Code Online (Sandbox Code Playgroud) 有没有办法简化这个尝试/除了与lambda一行?
alist = ['foo','bar','duh']
for j,i in enumerate(alist):
try:
iplus1 = i+alist[j+1]
except IndexError:
iplus1 = ""
Run Code Online (Sandbox Code Playgroud)
还有其他方式:
j = '' if IndexError else trg[pos]
Run Code Online (Sandbox Code Playgroud)