~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/registry.py

Add bzrlib.pyutils, which has get_named_object, a wrapper around __import__.

This is used to replace various ad hoc implementations of the same logic,
notably the version used in registry's _LazyObjectGetter which had a bug when
getting a module without also getting a member.  And of course, this new
function has unit tests, unlike the replaced code.

This also adds a KnownHooksRegistry subclass to provide a more natural home for
some other logic.

I'm not thrilled about the name of the new module or the new functions, but it's
hard to think of good names for such generic functionality.

Show diffs side-by-side

added added

removed removed

Lines of Context:
17
17
"""Classes to provide name-to-object registry-like support."""
18
18
 
19
19
 
 
20
from bzrlib.pyutils import get_named_object
 
21
 
 
22
 
20
23
class _ObjectGetter(object):
21
24
    """Maintain a reference to an object, and return the object on request.
22
25
 
58
61
        return the imported object.
59
62
        """
60
63
        if not self._imported:
61
 
            self._do_import()
 
64
            self._obj = get_named_object(self._module_name, self._member_name)
 
65
            self._imported = True
62
66
        return super(_LazyObjectGetter, self).get_obj()
63
67
 
64
 
    def _do_import(self):
65
 
        if self._member_name:
66
 
            segments = self._member_name.split('.')
67
 
            names = segments[0:1]
68
 
        else:
69
 
            names = [self._member_name]
70
 
        obj = __import__(self._module_name, globals(), locals(), names)
71
 
        if self._member_name:
72
 
            for segment in segments:
73
 
                obj = getattr(obj, segment)
74
 
        self._obj = obj
75
 
        self._imported = True
76
 
 
77
68
    def __repr__(self):
78
 
        return "<%s.%s object at %x, module=%r attribute=%r>" % (
 
69
        return "<%s.%s object at %x, module=%r attribute=%r imported=%r>" % (
79
70
            self.__class__.__module__, self.__class__.__name__, id(self),
80
 
            self._module_name, self._member_name)
 
71
            self._module_name, self._member_name, self._imported)
81
72
 
82
73
 
83
74
class Registry(object):