Python regex naming convention?

Is there an accepted naming convention for regular expressions in Python? Or if not, what suggestions on how to name them? I usually call them something like look_for_date or address_re , but I read a few places where using a suffix like _re in a variable name is not very good. It seems to me that the regex needs something to tell it the regex, because if you just named it date or address , you won't be able to do things that seem intuitive:

date = date_re.match(text)

+5
source share
1 answer

Compiled regular expressions are usually constants, so they must have the name UPPER_CASE_WITH_UNDERSCORES each PEP 8 . I tend to name them as they would fit; give an example from the code I recently wrote:

 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 clarifies what happens, VALID_CLOSURE_PATTERN says "this describes what we consider to be a valid closing pattern" and a line like this:

 if not VALID_CLOSURE_PATTERN.match(closure_pattern): 

describes what he actually does in plain English. So in your case you can write:

 date = VALID_DATE.match(text) 
+6
source

Source: https://habr.com/ru/post/1235313/


All Articles