~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/lazy_import.py

  • Committer: Andrew Bennetts
  • Date: 2010-10-08 08:15:14 UTC
  • mto: This revision was merged to the branch mainline in revision 5498.
  • Revision ID: andrew.bennetts@canonical.com-20101008081514-dviqzrdfwyzsqbz2
Split NEWS into per-release doc/en/release-notes/bzr-*.txt

Show diffs side-by-side

added added

removed removed

Lines of Context:
19
19
This includes waiting to import a module until it is actually used.
20
20
 
21
21
Most commonly, the 'lazy_import' function is used to import other modules
22
 
in an on-demand fashion. Typically use looks like::
23
 
 
 
22
in an on-demand fashion. Typically use looks like:
24
23
    from bzrlib.lazy_import import lazy_import
25
24
    lazy_import(globals(), '''
26
25
    from bzrlib import (
31
30
    import bzrlib.branch
32
31
    ''')
33
32
 
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.
 
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.
36
35
 
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).
 
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).
42
41
"""
43
42
 
44
 
from __future__ import absolute_import
45
 
 
46
43
 
47
44
class ScopeReplacer(object):
48
45
    """A lazy object that will replace itself in the appropriate scope.
53
50
 
54
51
    __slots__ = ('_scope', '_factory', '_name', '_real_obj')
55
52
 
56
 
    # If you to do x = y, setting this to False will disallow access to
57
 
    # members from the second variable (i.e. x). This should normally
58
 
    # be enabled for reasons of thread safety and documentation, but
59
 
    # will be disabled during the selftest command to check for abuse.
60
 
    _should_proxy = True
 
53
    # Setting this to True will allow you to do x = y, and still access members
 
54
    # from both variables. This should not normally be enabled, but is useful
 
55
    # when building documentation.
 
56
    _should_proxy = False
61
57
 
62
58
    def __init__(self, scope, factory, name):
63
59
        """Create a temporary object in the specified scope.
74
70
        object.__setattr__(self, '_real_obj', None)
75
71
        scope[name] = self
76
72
 
77
 
    def _resolve(self):
78
 
        """Return the real object for which this is a placeholder"""
 
73
    def _replace(self):
 
74
        """Actually replace self with other in the given scope"""
79
75
        name = object.__getattribute__(self, '_name')
80
 
        real_obj = object.__getattribute__(self, '_real_obj')
81
 
        if real_obj is None:
82
 
            # No obj generated previously, so generate from factory and scope.
 
76
        try:
83
77
            factory = object.__getattribute__(self, '_factory')
84
78
            scope = object.__getattribute__(self, '_scope')
85
 
            obj = factory(self, scope, name)
86
 
            if obj is self:
87
 
                raise errors.IllegalUseOfScopeReplacer(name, msg="Object tried"
88
 
                    " to replace itself, check it's not using its own scope.")
89
 
 
90
 
            # Check if another thread has jumped in while obj was generated.
91
 
            real_obj = object.__getattribute__(self, '_real_obj')
92
 
            if real_obj is None:
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)
97
 
                scope[name] = obj
98
 
                return obj
99
 
 
100
 
        # Raise if proxying is disabled as obj has already been generated.
101
 
        if not ScopeReplacer._should_proxy:
 
79
        except AttributeError, e:
 
80
            # Because ScopeReplacer objects only replace a single
 
81
            # item, passing them to another variable before they are
 
82
            # replaced would cause them to keep getting replaced
 
83
            # (only they are replacing the wrong variable). So we
 
84
            # make it forbidden, and try to give a good error.
102
85
            raise errors.IllegalUseOfScopeReplacer(
103
 
                name, msg="Object already replaced, did you assign it"
104
 
                          " to another variable?")
105
 
        return real_obj
 
86
                name, msg="Object already cleaned up, did you assign it"
 
87
                          " to another variable?",
 
88
                extra=e)
 
89
        obj = factory(self, scope, name)
 
90
        if obj is self:
 
91
            raise errors.IllegalUseOfScopeReplacer(name, msg="Object tried"
 
92
                " to replace itself, check it's not using its own scope.")
 
93
        if ScopeReplacer._should_proxy:
 
94
            object.__setattr__(self, '_real_obj', obj)
 
95
        scope[name] = obj
 
96
        return obj
 
97
 
 
98
    def _cleanup(self):
 
99
        """Stop holding on to all the extra stuff"""
 
100
        del self._factory
 
101
        del self._scope
 
102
        # We keep _name, so that we can report errors
 
103
        # del self._name
106
104
 
107
105
    def __getattribute__(self, attr):
108
 
        obj = object.__getattribute__(self, '_resolve')()
 
106
        obj = object.__getattribute__(self, '_real_obj')
 
107
        if obj is None:
 
108
            _replace = object.__getattribute__(self, '_replace')
 
109
            obj = _replace()
 
110
            _cleanup = object.__getattribute__(self, '_cleanup')
 
111
            _cleanup()
109
112
        return getattr(obj, attr)
110
113
 
111
114
    def __setattr__(self, attr, value):
112
 
        obj = object.__getattribute__(self, '_resolve')()
 
115
        obj = object.__getattribute__(self, '_real_obj')
 
116
        if obj is None:
 
117
            _replace = object.__getattribute__(self, '_replace')
 
118
            obj = _replace()
 
119
            _cleanup = object.__getattribute__(self, '_cleanup')
 
120
            _cleanup()
113
121
        return setattr(obj, attr, value)
114
122
 
115
123
    def __call__(self, *args, **kwargs):
116
 
        obj = object.__getattribute__(self, '_resolve')()
 
124
        _replace = object.__getattribute__(self, '_replace')
 
125
        obj = _replace()
 
126
        _cleanup = object.__getattribute__(self, '_cleanup')
 
127
        _cleanup()
117
128
        return obj(*args, **kwargs)
118
129
 
119
130
 
120
 
def disallow_proxying():
121
 
    """Disallow lazily imported modules to be used as proxies.
122
 
 
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.
126
 
 
127
 
    Only lazy imports that happen after this call are affected.
128
 
    """
129
 
    ScopeReplacer._should_proxy = False
130
 
 
131
 
 
132
131
class ImportReplacer(ScopeReplacer):
133
132
    """This is designed to replace only a portion of an import list.
134
133
 
161
160
            None, indicating the module is being imported.
162
161
        :param children: Children entries to be imported later.
163
162
            This should be a map of children specifications.
164
 
            ::
165
 
            
166
 
                {'foo':(['bzrlib', 'foo'], None,
167
 
                    {'bar':(['bzrlib', 'foo', 'bar'], None {})})
168
 
                }
169
 
 
170
 
        Examples::
171
 
 
 
163
            {'foo':(['bzrlib', 'foo'], None,
 
164
                {'bar':(['bzrlib', 'foo', 'bar'], None {})})
 
165
            }
 
166
        Examples:
172
167
            import foo => name='foo' module_path='foo',
173
168
                          member=None, children={}
174
169
            import foo.bar => name='foo' module_path='foo', member=None,
197
192
        module_path = object.__getattribute__(self, '_module_path')
198
193
        module_python_path = '.'.join(module_path)
199
194
        if member is not None:
200
 
            module = __import__(module_python_path, scope, scope, [member], level=0)
 
195
            module = __import__(module_python_path, scope, scope, [member])
201
196
            return getattr(module, member)
202
197
        else:
203
 
            module = __import__(module_python_path, scope, scope, [], level=0)
 
198
            module = __import__(module_python_path, scope, scope, [])
204
199
            for path in module_path[1:]:
205
200
                module = getattr(module, path)
206
201
 
375
370
def lazy_import(scope, text, lazy_import_class=None):
376
371
    """Create lazy imports for all of the imports in text.
377
372
 
378
 
    This is typically used as something like::
379
 
 
380
 
        from bzrlib.lazy_import import lazy_import
381
 
        lazy_import(globals(), '''
382
 
        from bzrlib import (
383
 
            foo,
384
 
            bar,
385
 
            baz,
386
 
            )
387
 
        import bzrlib.branch
388
 
        import bzrlib.transport
389
 
        ''')
 
373
    This is typically used as something like:
 
374
    from bzrlib.lazy_import import lazy_import
 
375
    lazy_import(globals(), '''
 
376
    from bzrlib import (
 
377
        foo,
 
378
        bar,
 
379
        baz,
 
380
        )
 
381
    import bzrlib.branch
 
382
    import bzrlib.transport
 
383
    ''')
390
384
 
391
385
    Then 'foo, bar, baz' and 'bzrlib' will exist as lazy-loaded
392
386
    objects which will be replaced with a real object on first use.