开发者

Is there an analogue of this function in Python standard modules?

I'm looking for a standard function (operator, decorator) that would be equivalent to the following hand-written function:

def defaulted(func, defaultVal):
  开发者_运维技巧 try:
      result = func()
   except: 
      result = defaultVal

   return result

Thanks!


There's nothing like that in the stdlib (to the best of my knowledge). For one thing, it's bad practice: you should never use a bare except. (Instead, specify the exceptions you want to catch; that way, you won't catch everything!)

Here's a decorator:

>>> def defaultval(error, value):
...     def decorator(func):
...             def defaulted(*args, **kwargs):
...                     try:
...                             return func(*args, **kwargs)
...                     except error:
...                             return value
...             return defaulted
...     return decorator
...
>>> @defaultval(NameError, "undefined")
... def get_var():
...     return name
...
>>> get_var()
'undefined'


No. Python's philosophy is that explicit is better than implicit. Most Python functions that are expected to throw exceptions regularly, like dict.__getitem__, provide equivalent versions that return a default value, like dict.get.

I've used the new with contexts for something like this before; the code looked like:

with ignoring(IOError, OSError):
    # some non-critical file operations

But I didn't need to return anything either. Generally, the whole-function level is a bad place for this, and by using decorators you'd block any chance at actually getting the error should you want to handle it more gracefully elsewhere.

Also, except: is extremely dangerous; you probably mean (at least) except Exception:, and probably something even more tightly scoped, like IOError or KeyError. Otherwise you will also catch things like Ctrl-C, SystemExit, and misspelled variable names.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜