From c81ca37dfccba9dd2863f8ec40414e0453bcc983 Mon Sep 17 00:00:00 2001 From: Todd Gamblin Date: Sat, 6 Feb 2021 00:22:46 -0800 Subject: version: precompile regexes in Version constructor --- lib/spack/spack/version.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/lib/spack/spack/version.py b/lib/spack/spack/version.py index d4deee78a9..321a03efc7 100644 --- a/lib/spack/spack/version.py +++ b/lib/spack/spack/version.py @@ -37,7 +37,10 @@ from spack.util.spack_yaml import syaml_dict __all__ = ['Version', 'VersionRange', 'VersionList', 'ver'] # Valid version characters -VALID_VERSION = r'[A-Za-z0-9_.-]' +VALID_VERSION = re.compile(r'[A-Za-z0-9_.-]') + +# regex for version segments +SEGMENT_REGEX = re.compile(r'[a-zA-Z]+|[0-9]+') # Infinity-like versions. The order in the list implies the comparison rules infinity_versions = ['develop', 'main', 'master', 'head', 'trunk'] @@ -97,9 +100,10 @@ class Version(object): """Class to represent versions""" def __init__(self, string): - string = str(string) + if not isinstance(string, str): + string = str(string) - if not re.match(VALID_VERSION, string): + if not VALID_VERSION.match(string): raise ValueError("Bad characters in version string: %s" % string) # preserve the original string, but trimmed. @@ -107,12 +111,11 @@ class Version(object): self.string = string # Split version into alphabetical and numeric segments - segment_regex = r'[a-zA-Z]+|[0-9]+' - segments = re.findall(segment_regex, string) + segments = SEGMENT_REGEX.findall(string) self.version = tuple(int_if_int(seg) for seg in segments) # Store the separators from the original version string as well. - self.separators = tuple(re.split(segment_regex, string)[1:]) + self.separators = tuple(SEGMENT_REGEX.split(string)[1:]) @property def dotted(self): -- cgit v1.2.3-60-g2f50