Type of regular expression

Peter Otten __peter__ at web.de
Thu Jul 1 11:50:50 EDT 2004


Joakim Hove wrote:

> I wondered how I could test wether an argument was of type compiled
> regexp:

Both strings and compiled regular expressions can be compiled:

>>> import re
>>> r = re.compile("abc")
>>> s = re.compile(r)
>>> r is s
True

Therefore I would not test beforehand, just rely on re.compile() to know
what it can deal with:

>>> def do_something(s):
...     try:
...             s = re.compile(s)
...     except TypeError:
...             sys.exit("Something went wrong")
...     # more stuff
...
>>> do_something("abc")
>>> do_something(r)
>>> do_something(1)
Something went wrong

Peter




More information about the Python-list mailing list