在Python中,可以使用单行来以简单,直观的方式设置具有特殊条件(例如默认值或条件)的值.
result = 0 or "Does not exist." # "Does not exist."
result = "Found user!" if user in user_list else "User not found."
Run Code Online (Sandbox Code Playgroud)
是否有可能编写一个捕获异常的类似语句?
from json import loads
result = loads('{"value": true}') or "Oh no, explosions occurred!"
# {'value': True}
result = loads(None) or "Oh no, explosions occurred!"
# "Oh no, explosions occurred!" is desired, but a TypeError is raised.
Run Code Online (Sandbox Code Playgroud) 我有一个代码,我尝试访问资源,但有时它不可用,并导致异常.我尝试使用上下文管理器实现重试引擎,但我无法处理__enter__上下文表单上下文管理器中调用者引发的异常.
class retry(object):
def __init__(self, retries=0):
self.retries = retries
self.attempts = 0
def __enter__(self):
for _ in range(self.retries):
try:
self.attempts += 1
return self
except Exception as e:
err = e
def __exit__(self, exc_type, exc_val, traceback):
print 'Attempts', self.attempts
Run Code Online (Sandbox Code Playgroud)
这是一些只引发异常的例子(我希望处理的那个)
>>> with retry(retries=3):
... print ok
...
Attempts 1
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
NameError: name 'ok' is not defined
>>>
>>> with retry(retries=3):
... open('/file')
...
Attempts 1
Traceback …Run Code Online (Sandbox Code Playgroud) 我是Python的新手,仍然在学习技巧。
我如何将以下代码转换为单个内衬,在Python中可以吗?必须有一种整齐的方法来做到这一点。
try:
image_file = self.request.files['image_path']
except:
image_file = None
Run Code Online (Sandbox Code Playgroud)