简体   繁体   English

Python 正则表达式的命名约定?

[英]Naming convention for Python regular expressions?

Is there an accepted naming convention for regular expressions in Python? Python 中的正则表达式是否有公认的命名约定? Or if there's not, what are some suggestions on how to name them?或者如果没有,关于如何命名它们有什么建议?

Usually I name them something like look_for_date or address_re but I've read several places that using a suffix like '_re' in a variable name isn't good.通常我将它们命名为look_for_dateaddress_re类的东西,但我读过几个地方,在变量名中使用像“_re”这样的后缀并不好。 To me it seems like the regex needs something to indicate it's a regex, since if you named it just date or address , you wouldn't be able to do stuff like this, which seems intuitive:对我来说,正则表达式似乎需要一些东西来表明它是一个正则表达式,因为如果你只是将它命名为dateaddress ,你将无法做这样的事情,这看起来很直观:

date = date_re.match(text)

Compiled regular expressions are generally constants , so should have an UPPER_CASE_WITH_UNDERSCORES name per PEP 8 .编译后的正则表达式通常是常量,因此每个PEP 8应该有一个UPPER_CASE_WITH_UNDERSCORES名称。 I tend to name them for what they would match;我倾向于根据它们匹配的内容来命名它们; to give an example from some code I wrote recently:举一个我最近写的一些代码的例子:

import re

VALID_CLOSURE_PATTERN = re.compile(r'''
    ^\d{2}    # starts with two digits 0-9
    [NY]{4}$  # followed by four Y/N characters
''', re.IGNORECASE + re.VERBOSE)


class RoadClosure(object):

    def __init__(self, ..., closure_pattern):
        """Initialise the new instance."""
        if not VALID_CLOSURE_PATTERN.match(closure_pattern):
            raise ValueError('invalid closure pattern: {!r}'.format(closure_pattern))
       ...

...

I think this makes it pretty clear what's going on, VALID_CLOSURE_PATTERN communicates "this describes what we would consider to be a valid closure pattern" and a line like:我认为这很清楚发生了什么, VALID_CLOSURE_PATTERN传达“这描述了我们认为是有效的闭包模式”和如下一行:

if not VALID_CLOSURE_PATTERN.match(closure_pattern):

describes what it's actually doing in close to plain English.用接近简单的英语描述它实际上在做什么。 So in your case, you might write:所以在你的情况下,你可能会写:

date = VALID_DATE.match(text)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM