Is there an accepted naming convention for regular expressions in 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. 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:
date = date_re.match(text)
Compiled regular expressions are generally constants, so should have an UPPER_CASE_WITH_UNDERSCORES
name per PEP 8. 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:
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With