~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/lazy_import.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2011-08-17 18:13:57 UTC
  • mfrom: (5268.7.29 transport-segments)
  • Revision ID: pqm@pqm.ubuntu.com-20110817181357-y5q5eth1hk8bl3om
(jelmer) Allow specifying the colocated branch to use in the branch URL,
 and retrieving the branch name using ControlDir._get_selected_branch.
 (Jelmer Vernooij)

Show diffs side-by-side

added added

removed removed

Lines of Context:
41
41
to inherit from them).
42
42
"""
43
43
 
44
 
from __future__ import absolute_import
45
 
 
46
44
 
47
45
class ScopeReplacer(object):
48
46
    """A lazy object that will replace itself in the appropriate scope.
53
51
 
54
52
    __slots__ = ('_scope', '_factory', '_name', '_real_obj')
55
53
 
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
 
54
    # Setting this to True will allow you to do x = y, and still access members
 
55
    # from both variables. This should not normally be enabled, but is useful
 
56
    # when building documentation.
 
57
    _should_proxy = False
61
58
 
62
59
    def __init__(self, scope, factory, name):
63
60
        """Create a temporary object in the specified scope.
74
71
        object.__setattr__(self, '_real_obj', None)
75
72
        scope[name] = self
76
73
 
77
 
    def _resolve(self):
78
 
        """Return the real object for which this is a placeholder"""
 
74
    def _replace(self):
 
75
        """Actually replace self with other in the given scope"""
79
76
        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.
 
77
        try:
83
78
            factory = object.__getattribute__(self, '_factory')
84
79
            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:
 
80
        except AttributeError, e:
 
81
            # Because ScopeReplacer objects only replace a single
 
82
            # item, passing them to another variable before they are
 
83
            # replaced would cause them to keep getting replaced
 
84
            # (only they are replacing the wrong variable). So we
 
85
            # make it forbidden, and try to give a good error.
102
86
            raise errors.IllegalUseOfScopeReplacer(
103
 
                name, msg="Object already replaced, did you assign it"
104
 
                          " to another variable?")
105
 
        return real_obj
 
87
                name, msg="Object already cleaned up, did you assign it"
 
88
                          " to another variable?",
 
89
                extra=e)
 
90
        obj = factory(self, scope, name)
 
91
        if obj is self:
 
92
            raise errors.IllegalUseOfScopeReplacer(name, msg="Object tried"
 
93
                " to replace itself, check it's not using its own scope.")
 
94
        if ScopeReplacer._should_proxy:
 
95
            object.__setattr__(self, '_real_obj', obj)
 
96
        scope[name] = obj
 
97
        return obj
 
98
 
 
99
    def _cleanup(self):
 
100
        """Stop holding on to all the extra stuff"""
 
101
        del self._factory
 
102
        del self._scope
 
103
        # We keep _name, so that we can report errors
 
104
        # del self._name
106
105
 
107
106
    def __getattribute__(self, attr):
108
 
        obj = object.__getattribute__(self, '_resolve')()
 
107
        obj = object.__getattribute__(self, '_real_obj')
 
108
        if obj is None:
 
109
            _replace = object.__getattribute__(self, '_replace')
 
110
            obj = _replace()
 
111
            _cleanup = object.__getattribute__(self, '_cleanup')
 
112
            _cleanup()
109
113
        return getattr(obj, attr)
110
114
 
111
115
    def __setattr__(self, attr, value):
112
 
        obj = object.__getattribute__(self, '_resolve')()
 
116
        obj = object.__getattribute__(self, '_real_obj')
 
117
        if obj is None:
 
118
            _replace = object.__getattribute__(self, '_replace')
 
119
            obj = _replace()
 
120
            _cleanup = object.__getattribute__(self, '_cleanup')
 
121
            _cleanup()
113
122
        return setattr(obj, attr, value)
114
123
 
115
124
    def __call__(self, *args, **kwargs):
116
 
        obj = object.__getattribute__(self, '_resolve')()
 
125
        _replace = object.__getattribute__(self, '_replace')
 
126
        obj = _replace()
 
127
        _cleanup = object.__getattribute__(self, '_cleanup')
 
128
        _cleanup()
117
129
        return obj(*args, **kwargs)
118
130
 
119
131
 
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
132
class ImportReplacer(ScopeReplacer):
133
133
    """This is designed to replace only a portion of an import list.
134
134
 
197
197
        module_path = object.__getattribute__(self, '_module_path')
198
198
        module_python_path = '.'.join(module_path)
199
199
        if member is not None:
200
 
            module = __import__(module_python_path, scope, scope, [member], level=0)
 
200
            module = __import__(module_python_path, scope, scope, [member])
201
201
            return getattr(module, member)
202
202
        else:
203
 
            module = __import__(module_python_path, scope, scope, [], level=0)
 
203
            module = __import__(module_python_path, scope, scope, [])
204
204
            for path in module_path[1:]:
205
205
                module = getattr(module, path)
206
206