[Python-Dev] Proposal: thread.get_dict

Jim Fulton jim at zope.com
Mon Jun 28 13:52:34 EDT 2004

Armin Rigo wrote:
> Hello Jim,
> On Mon, Jun 28, 2004 at 10:50:08AM -0400, Jim Fulton wrote:
>>I propose, for 2.4, to add a get_dict method to the thread
>>module that will return this dictionary.  This will be
>>implemented via a call to PyThreadState_GetDict.
> I am pretty sure that some extension modules would badly crash if arbitrary
> Python code would be allowed to temper with the data that they store there.  

AFAIK, only one bit of extension code uses this data.

But, of course, applications that use this data would have to
be disciplined about picking keys to avoid conflict. This is actually
pretty easy.  In Zope 3, when a bit of code wants to place a value into a
shared namespace, it uses it's package dotted name as a prefix for
the key.  In this way, code from different packages don't accidentelly
use the same key.

> Actually, to encourage encapsulation I'd push for another interface.  For
> example there could be a constructor thread.Locals which you invoke once at a
> global level; it returns an object whose attributes are then local to the
> thread.  An unrelated module's call to thread.Locals returns an unrelated
> object.
> To polish the idea more, thread.Locals would be a class that you can also
> inherit from to use the functionality in your own classes.  Something along
> the lines of the C version of
> class Locals(object):
>   def __getattribute__(self, attr):
>     d = PyThreadState_GetDict()
>     attrs = d.setdefault(self, {})   # use 'self' as the key
>     try:
>       return attrs[attr]
>     except KeyError:
>       ...
>   def __setattr__(self, attr, value):
>     ...
>   def __delattr__(self, attr):
>     ...

This is a fine idea, but I think a simpler mechanism will work
just as well and avoid the extra dictionary lookup that your suggestion
introduces.  I have an application in which these lookups will be done a
lot and I want to minimize overhead.


Jim Fulton           mailto:jim at zope.com       Python Powered!
CTO                  (540) 361-1714            http://www.python.org
Zope Corporation     http://www.zope.com       http://www.zope.org

More information about the Python-Dev mailing list