使用Context Manager进行控制流程

Kur*_*ler 5 python python-3.x

我想知道在python中是否可以使用这样的东西(3.2,如果那是相关的).

with assign_match('(abc)(def)', 'abcdef') as (a, b):
    print(a, b)
Run Code Online (Sandbox Code Playgroud)

行为在哪里:

  • 如果正则表达式匹配,则将正则表达式组分配给ab
    • 如果那里存在不匹配,则会抛出异常
  • 如果匹配None,它将完全绕过上下文

我的目标基本上是一种非常简洁的上下文行为方式.

我尝试制作以下上下文管理器:

import re

class assign_match(object):
    def __init__(self, regex, string):
        self.regex = regex
        self.string = string
    def __enter__(self):
        result = re.match(self.regex, self.string)
        if result is None:
            raise ValueError
        else:
            return result.groups()
    def __exit__(self, type, value, traceback):
        print(self, type, value, traceback) #testing purposes. not doing anything here.

with assign_match('(abc)(def)', 'abcdef') as (a, b):
    print(a, b) #prints abc def
with assign_match('(abc)g', 'abcdef') as (a, b): #raises ValueError
    print(a, b)
Run Code Online (Sandbox Code Playgroud)

它实际上与正则表达式匹配时的情况完全一致,但是,正如您所看到的,它会抛出ValueError如果没有匹配的情况.有什么方法可以让它"跳"到退出序列吗?

谢谢!!

Kur*_*ler 4

啊! 也许对它的解释为我澄清了这个问题。我只是使用 if 语句而不是 with 语句。

def assign_match(regex, string):
    match = re.match(regex, string)
    if match is None:
        raise StopIteration
    else:
        yield match.groups()

for a in assign_match('(abc)(def)', 'abcdef'):
    print(a)
Run Code Online (Sandbox Code Playgroud)

给出了我想要的行为。将其留在这里以防其他人想从中受益。(Mods,如果不相关,请随意删除等)

编辑:实际上,这个解决方案有一个相当大的缺陷。我在 for 循环中执行此行为。所以这阻止我做:

for string in lots_of_strings:
    for a in assign_match('(abc)(def)', string):
        do_my_work()
        continue # breaks out of this for loop instead of the parent
    other_work() # behavior i want to skip if the match is successful
Run Code Online (Sandbox Code Playgroud)

因为 continue 现在会跳出此循环,而不是父 for 循环。如果有人有建议,我很想听听!

EDIT2:好吧,这次真的弄清楚了。

from contextlib import contextmanager
import re

@contextmanager
def assign_match(regex, string):
    match = re.match(regex, string)
    if match:
        yield match.groups()

for i in range(3):
    with assign_match('(abc)(def)', 'abcdef') as a:
#    for a in assign_match('(abc)(def)', 'abcdef'):
        print(a)
        continue
    print(i)
Run Code Online (Sandbox Code Playgroud)

抱歉发了这个帖子——我发誓在发帖之前我真的感觉很困难。:-) 希望其他人会觉得这很有趣!

  • 显式的“raise StopIteration”是不必要的。`if match: Yield match.groups()` 就足够了。 (2认同)