Is Python re thread-safe?

python, regex

Solution

I don't think there is an authoritative answer—other than digging around in the source, which gets you answers for existing versions of Python but not necessarily future ones—since at least some parts of some versions of the regular expression module are written in C (at least for CPython; for Jython, for instance, who knows?) and nobody seems to have made any promises about them.

In practice I have not seen any bits of the RE code that are not thread-safe, and your later example with the `GLOBAL_VAR.sub` call is "almost certainly" thread-safe. But ... there's still that darned lack of written promises. :-)

Problem

I tried googling but gotten no authoritative answer. Can someone confirm that the `re` module http://docs.python.org/2/library/re.html is thread-safe? More specifically, which functions are and which are not? Also, can I reuse a single global compiled re object to do `sub`, `search`, etc. safely across threads? Seems like there is still no clear answer? Ok, a more specific example: ``` class MyClass: GLOBAL_VAR = re.compile(...) def clean(self, value): return MyClass.GLOBAL_VAR.sub('', value) ``` Will this work as expected when multiple threads call clean at the same time?

Original source