13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
17
"""Functionality to create lazy evaluation objects.
19
19
This includes waiting to import a module until it is actually used.
21
21
Most commonly, the 'lazy_import' function is used to import other modules
22
in an on-demand fashion. Typically use looks like:
22
in an on-demand fashion. Typically use looks like::
23
24
from bzrlib.lazy_import import lazy_import
24
25
lazy_import(globals(), '''
25
26
from bzrlib import (
30
31
import bzrlib.branch
33
Then 'errors, osutils, branch' and 'bzrlib' will exist as lazy-loaded
34
objects which will be replaced with a real object on first use.
34
Then 'errors, osutils, branch' and 'bzrlib' will exist as lazy-loaded
35
objects which will be replaced with a real object on first use.
36
In general, it is best to only load modules in this way. This is because
37
it isn't safe to pass these variables to other functions before they
38
have been replaced. This is especially true for constants, sometimes
39
true for classes or functions (when used as a factory, or you want
40
to inherit from them).
37
In general, it is best to only load modules in this way. This is because
38
it isn't safe to pass these variables to other functions before they
39
have been replaced. This is especially true for constants, sometimes
40
true for classes or functions (when used as a factory, or you want
41
to inherit from them).
44
from __future__ import absolute_import
44
47
class ScopeReplacer(object):
45
48
"""A lazy object that will replace itself in the appropriate scope.
59
68
It will be passed (self, scope, name)
60
69
:param name: The variable name in the given scope.
63
self._factory = factory
71
object.__setattr__(self, '_scope', scope)
72
object.__setattr__(self, '_factory', factory)
73
object.__setattr__(self, '_name', name)
74
object.__setattr__(self, '_real_obj', None)
68
"""Actually replace self with other in the given scope"""
78
"""Return the real object for which this is a placeholder"""
69
79
name = object.__getattribute__(self, '_name')
80
real_obj = object.__getattribute__(self, '_real_obj')
82
# No obj generated previously, so generate from factory and scope.
71
83
factory = object.__getattribute__(self, '_factory')
72
84
scope = object.__getattribute__(self, '_scope')
73
except AttributeError, e:
74
# Because ScopeReplacer objects only replace a single
75
# item, passing them to another variable before they are
76
# replaced would cause them to keep getting replaced
77
# (only they are replacing the wrong variable). So we
78
# make it forbidden, and try to give a good error.
85
obj = factory(self, scope, name)
87
raise errors.IllegalUseOfScopeReplacer(name, msg="Object tried"
88
" to replace itself, check it's not using its own scope.")
90
# Check if another thread has jumped in while obj was generated.
91
real_obj = object.__getattribute__(self, '_real_obj')
93
# Still no prexisting obj, so go ahead and assign to scope and
94
# return. There is still a small window here where races will
95
# not be detected, but safest to avoid additional locking.
96
object.__setattr__(self, '_real_obj', obj)
100
# Raise if proxying is disabled as obj has already been generated.
101
if not ScopeReplacer._should_proxy:
79
102
raise errors.IllegalUseOfScopeReplacer(
80
name, msg="Object already cleaned up, did you assign it"
81
" to another variable?",
83
obj = factory(self, scope, name)
88
"""Stop holding on to all the extra stuff"""
91
# We keep _name, so that we can report errors
103
name, msg="Object already replaced, did you assign it"
104
" to another variable?")
94
107
def __getattribute__(self, attr):
95
_replace = object.__getattribute__(self, '_replace')
97
_cleanup = object.__getattribute__(self, '_cleanup')
108
obj = object.__getattribute__(self, '_resolve')()
99
109
return getattr(obj, attr)
111
def __setattr__(self, attr, value):
112
obj = object.__getattribute__(self, '_resolve')()
113
return setattr(obj, attr, value)
101
115
def __call__(self, *args, **kwargs):
102
_replace = object.__getattribute__(self, '_replace')
104
_cleanup = object.__getattribute__(self, '_cleanup')
116
obj = object.__getattribute__(self, '_resolve')()
106
117
return obj(*args, **kwargs)
120
def disallow_proxying():
121
"""Disallow lazily imported modules to be used as proxies.
123
Calling this function might cause problems with concurrent imports
124
in multithreaded environments, but will help detecting wasteful
125
indirection, so it should be called when executing unit tests.
127
Only lazy imports that happen after this call are affected.
129
ScopeReplacer._should_proxy = False
109
132
class ImportReplacer(ScopeReplacer):
110
133
"""This is designed to replace only a portion of an import list.
138
161
None, indicating the module is being imported.
139
162
:param children: Children entries to be imported later.
140
163
This should be a map of children specifications.
141
{'foo':(['bzrlib', 'foo'], None,
142
{'bar':(['bzrlib', 'foo', 'bar'], None {})})
166
{'foo':(['bzrlib', 'foo'], None,
167
{'bar':(['bzrlib', 'foo', 'bar'], None {})})
145
172
import foo => name='foo' module_path='foo',
146
173
member=None, children={}
147
174
import foo.bar => name='foo' module_path='foo', member=None,
151
178
from foo import bar, baz would get translated into 2 import
152
179
requests. On for 'name=bar' and one for 'name=baz'
154
if member is not None:
155
assert not children, \
156
'Cannot supply both a member and children'
181
if (member is not None) and children:
182
raise ValueError('Cannot supply both a member and children')
158
self._import_replacer_children = children
159
self._member = member
160
self._module_path = module_path
184
object.__setattr__(self, '_import_replacer_children', children)
185
object.__setattr__(self, '_member', member)
186
object.__setattr__(self, '_module_path', module_path)
162
188
# Indirecting through __class__ so that children can
163
189
# override _import (especially our instrumented version)
171
197
module_path = object.__getattribute__(self, '_module_path')
172
198
module_python_path = '.'.join(module_path)
173
199
if member is not None:
174
module = __import__(module_python_path, scope, scope, [member])
200
module = __import__(module_python_path, scope, scope, [member], level=0)
175
201
return getattr(module, member)
177
module = __import__(module_python_path, scope, scope, [])
203
module = __import__(module_python_path, scope, scope, [], level=0)
178
204
for path in module_path[1:]:
179
205
module = getattr(module, path)