需要 Pythonic 重构建议

问题描述 投票:0回答:1

我正在为忽略前导码的文件编写一个标记器。这些文件是用 Markdown 编写的,H1 标题中有一个关键字列表,可以更改解析器的状态。当遇到 EOF 时,状态机返回到忽略状态并查找关键字标题。

我决定制作一个通用包以供将来使用,因此我编写了以下 peek 代码:

def peek(self):
        while True:
            if (self.skip_white_space and self.expect_type('WHITE_SPACE') or \
            self.skip_EOF and self.expect_type('EOF')) and \
            not self.is_end():
                self.consume()
                continue
            break
        return None if self.is_end() else self.lines[self.line][self.column]

有更好的方法吗?无限循环是丑陋的。巨大的 if 条件也很糟糕。

我尝试学习Python,但显然失败了。我期待的是不是粪便的东西。

python refactoring tokenize
1个回答
0
投票

让你的循环更加Pythonic。你可以这样重写该方法:

def peek(self):
    def skip_next() -> bool:
        conf = self.configuration
        return (
            (conf['skip_white_space'] and self.expect_type('WHITE_SPACE'))
            or (conf['skip_EOF'] and self.expect_type('EOF'))
        )
    
    while not self.out_of_tokens() and skip_next():
        self.consume()
    
    return (
        None if self.out_of_tokens()
        else self.tokens[self.line][self.column]
    )

在这种情况下,

while
条件将完成所有操作,无需使用
continue
break
。我还将您的长
if
语句放在一个单独的函数中,以便于阅读。

检查一下,如果有帮助请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.