Is Python re thread-safe?

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. :-)


Yes, They are thread safe, Because there is just a _cache dictionary between functions, each functions will use it to look up the generated value, and if the value was not in _cache, functions will generate value and put it to the _cache dictionary, and it won't violate the thread safety

Tags:

Python

Regex