Detecting RegEx across Python versions (fwd)

Lulu of the Lotus-Eaters mertz at gnosis.cx
Fri Feb 16 18:53:13 CET 2001


I asked earlier:
> I have done the following, but would welcome something more
> elegant
>
>     [...]
>     # kludge to detect a regular expression across python versions
>     elif sys.version[0]=='1' and isinstance(pattern, re.RegexObject):
>         if pattern.match(name):
>             files.append(fname)
>     elif sys.version[0]=='2' and type(pattern)==type(re.compile('')):
>         if pattern.match(name):
>             files.append(fname)
>     elif type(pattern) is StringType:
>         if fnmatch.fnmatch(name, pattern):
>             files.append(fname)

To which the /F-bot generously replied:
| if isinstance(pattern, type("")):
|     if fnmatch.fnmatch(name, pattern):
|         files.append(fname)
| else:
|     if pattern.match(name):
|         files.append(fname)
| ----
| try:
|     if pattern.match(name):
|         files.append(fname)
| except AttributeError:
|     if fnmatch.fnmatch(name, pattern):
|         files.append(fname)
| ----
| if isinstance(pattern, type("")):
|     pattern = re.compile(fnmatch.translate(pattern))
| if pattern.match(name):

Lundh's solutions are more compact, and probably per my request of more
elegant.  But I probably should have been explicit with the enthymeme:
I would like something that is both more elegant AND no less paranoid.

That is, I only want to glob a genuine string, and I only want to regex
a genuine re object.  Being the suspicious type--wholly untrusting of my
callers :-) (since they might be me)--I don't want to let this cause
uncaught exceptions on the wrong type for pattern.  For example (/F's
first example, roughly):

    >>> pattern = open('spam','w')
    >>> if isinstance(pattern, type('')):
    ...     print "Got String"
    ... else:
    ...     if pattern.match('spam'):
    ...         print "Got RegEx"
    ...
    Traceback (innermost last):
      File "<stdin>", line 4, in ?
    AttributeError: match

My own inelegant code would just pass things through without matching,
but also without raising errors.  /F's other versions will raise similar
uncaught errors.

I suppose I could wrap another 'try' around things, and catch those
non-string/non-regex things.  But I'd still really love to be able to
write a clean, version independent, expression of "X is a compiled regex
(and not any other thing)."

Yours, Lulu...




More information about the Python-list mailing list