加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 使用Context Manager进行控制流

发布时间:2020-12-16 22:04:05 所属栏目:Python 来源:网络整理
导读:我想知道在python中是否可以使用这样的东西(3.2,如果那是相关的). with assign_match('(abc)(def)','abcdef') as (a,b): print(a,b) 行为在哪里: 如果正则表达式匹配,则将正则表达式组分配给a和b 如果那里存在不匹配,则会抛出异常 如果匹配为None,则完全绕

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

with assign_match('(abc)(def)','abcdef') as (a,b):
    print(a,b)

行为在哪里:

>如果正则表达式匹配,则将正则表达式组分配给a和b

>如果那里存在不匹配,则会抛出异常

>如果匹配为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,traceback) #testing purposes. not doing anything here.

with assign_match('(abc)(def)',b) #prints abc def
with assign_match('(abc)g',b): #raises ValueError
    print(a,b)

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

谢谢!!

最佳答案
啊!也许在SO上解释它为我澄清了问题.我只使用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)

准确地给出了我想要的行为.将此留在这里以防其他人想要从中受益. (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

因为continue现在突破了这个循环而不是父for循环.如果有人有建议,我很乐意听到!

EDIT2:好的,这一次想出来了.

from contextlib import contextmanager
import re

@contextmanager
def assign_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)

对不起该帖子 – 我发誓,在发布之前,我感到非常困惑. :-)希望别人会觉得这很有意思!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读