__builtins__ thread-safe / __builtins__ as function?

Juergen Bartholomae bartholomae.juergen at googlemail.com
Sun Oct 14 06:36:28 EDT 2012


>> One possible solution  is to somehow redirect every __builtins__ to a
>> function that returns a different __builtins__ dictionary for each thread
>> (such a function already exists).

>How exactly does the code reference it? If they're simply referring to
>the name __builtins__ at module level, you ought to be able to import
>the module, then assign some_module.__builtins__ to your thread-local
>object, then call code in it as normal.

>An interesting problem, and one where monkeypatching is, imho, justified.

>ChrisA

Hello, and thanks for your answer.
Unfortunately, replacing __builtins__ at import time won't do, because
external modules (that is, .py) get imported only once when they are
accessed by the first thread, which includes (of course) setting up of
__dict__ and __builtins__. When a second thread later accesses this
module, it has the same variables in __builtins__ that were added by
the same module in first thread
And if the second thread then changes the values, I can see these
same changes in the first thread.
-> The problem is that __builtins__ are global, not thread-safe.

The only solution I can see is therfor redirecting __builtins__ to a
function which returns a different dictionary for each thread, e.g.
by intercepting __builtins__-calls with __readattr__.
To do this, I would need my own class to define __readattr__ in
since (as far as I know) I can't define __readattr__ in a module,
and I can't change metaclass <module> of course.

I really don't know how to get around this problem...
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20121014/29fd7aa1/attachment.html>


More information about the Python-list mailing list