Python函数与Cpython命令实现

Python函数与Cpython命令实现,python,python-3.x,cpython,contextmanager,Python,Python 3.x,Cpython,Contextmanager,在哪些上下文中,有助于实现新命令,例如可能的忽略[Excepions],而不是将其定义为函数 “忽略”上下文管理器: import contextlib @contextlib.contextmanager def ignored(*exceptions): try: yield except exceptions: pass with ignored(IndexError, KeyError): ## inside code here

在哪些上下文中,有助于实现新命令,例如可能的
忽略[Excepions]
,而不是将其定义为函数

“忽略”上下文管理器:

import contextlib

@contextlib.contextmanager
def ignored(*exceptions):
    try:
        yield
    except exceptions:
        pass
with ignored(IndexError, KeyError):
    ## inside code here
ignored IndexError, KeyError:
    ## inside code here
用法:

import contextlib

@contextlib.contextmanager
def ignored(*exceptions):
    try:
        yield
    except exceptions:
        pass
with ignored(IndexError, KeyError):
    ## inside code here
ignored IndexError, KeyError:
    ## inside code here
可能的备选方案:

import contextlib

@contextlib.contextmanager
def ignored(*exceptions):
    try:
        yield
    except exceptions:
        pass
with ignored(IndexError, KeyError):
    ## inside code here
ignored IndexError, KeyError:
    ## inside code here

这只会让事情变得更干净

检查这两个实现

with file("/tmp/foo", "w") as foo:
    print >> foo, "Hello!"
这基本上相当于:

foo = file("/tmp/foo", "w")
try:
    print >> foo, "Hello!"
finally:
    foo.close()
但是你更愿意用哪一种呢


查看进一步阅读

您打算如何实施替代方案?你打算更新python解析器吗?@tdelaney是的,我想知道你对优点和缺点的看法……摆弄python解析器是很困难的,然后你会得到一个非标准的解释器,而这个解释器可能不会被理解。除了用于练习的玩具实现之外,我认为这样做没有任何好处。如果你喜欢这个挑战,就去吧,但我不认为它对其他人有用!啊好的。我会接受@tdelaney的评论。总结得很好!