Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does re.compile() or any given Python library call throw an exception?

I can't tell from the Python documentation whether the re.compile(x) function may throw an exception (assuming you pass in a string). I imagine there is something that could be considered an invalid regular expression. The larger question is, where do I go to find if a given Python library call may throw exception(s) and what those are?

like image 728
postfuturist Avatar asked Sep 12 '08 01:09

postfuturist


People also ask

What does re compile do in Python?

Python's re. compile() method is used to compile a regular expression pattern provided as a string into a regex pattern object ( re. Pattern ). Later we can use this pattern object to search for a match inside different target strings using regex methods such as a re.

Why do we need re compile?

The re. compile(pattern, repl, string): We can combine a regular expression pattern into pattern objects, which can be used for pattern matching. It also helps to search a pattern again without rewriting it.

What does the function re search do in Python?

What does the function re.search do? Explanation: It will look for the pattern at any position in the string.

Is re built in Python?

Python has a built-in package called re , which can be used to work with Regular Expressions.


2 Answers

Well, re.compile certainly may:

>>> import re
>>> re.compile('he(lo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python25\lib\re.py", line 180, in compile
    return _compile(pattern, flags)
  File "C:\Python25\lib\re.py", line 233, in _compile
    raise error, v # invalid expression
sre_constants.error: unbalanced parenthesis

The documentation does support this, in a roundabout way - check the bottom of the "Module Contents" page for (brief) description of the error exception.

Unfortunately, I don't have any answer to the general question. I suppose the documentation for the various modules varies in quality and thoroughness. If there were particular modules you were interested in, you might be able to decompile them (if written in Python) or even look at the source, if they're in the standard library.

like image 144
Blair Conrad Avatar answered Oct 02 '22 13:10

Blair Conrad


Unlike Java, where there are exceptions that must be declared to be raised (and some that don't have to be, but that's another story), any Python code may raise any exception at any time.

There are a list of built-in exceptions, which generally has some description of when these exceptions might be raised. Its up to you as to how much exception handling you will do, and if you will handle stuff gracefully, or just fail with a traceback.

like image 40
Matthew Schinckel Avatar answered Oct 02 '22 15:10

Matthew Schinckel