Add python-eventlet 0.16.1
[packages/trusty/python-eventlet.git] / eventlet / eventlet / corolocal.py
1 import weakref
2
3 from eventlet import greenthread
4
5 __all__ = ['get_ident', 'local']
6
7
8 def get_ident():
9     """ Returns ``id()`` of current greenlet.  Useful for debugging."""
10     return id(greenthread.getcurrent())
11
12
13 # the entire purpose of this class is to store off the constructor
14 # arguments in a local variable without calling __init__ directly
15 class _localbase(object):
16     __slots__ = '_local__args', '_local__greens'
17
18     def __new__(cls, *args, **kw):
19         self = object.__new__(cls)
20         object.__setattr__(self, '_local__args', (args, kw))
21         object.__setattr__(self, '_local__greens', weakref.WeakKeyDictionary())
22         if (args or kw) and (cls.__init__ is object.__init__):
23             raise TypeError("Initialization arguments are not supported")
24         return self
25
26
27 def _patch(thrl):
28     greens = object.__getattribute__(thrl, '_local__greens')
29     # until we can store the localdict on greenlets themselves,
30     # we store it in _local__greens on the local object
31     cur = greenthread.getcurrent()
32     if cur not in greens:
33         # must be the first time we've seen this greenlet, call __init__
34         greens[cur] = {}
35         cls = type(thrl)
36         if cls.__init__ is not object.__init__:
37             args, kw = object.__getattribute__(thrl, '_local__args')
38             thrl.__init__(*args, **kw)
39     object.__setattr__(thrl, '__dict__', greens[cur])
40
41
42 class local(_localbase):
43     def __getattribute__(self, attr):
44         _patch(self)
45         return object.__getattribute__(self, attr)
46
47     def __setattr__(self, attr, value):
48         _patch(self)
49         return object.__setattr__(self, attr, value)
50
51     def __delattr__(self, attr):
52         _patch(self)
53         return object.__delattr__(self, attr)