1
# Copyright (C) 2006-2010 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""Classes to provide name-to-object registry-like support."""
19
from __future__ import absolute_import
21
from .pyutils import get_named_object
24
class _ObjectGetter(object):
25
"""Maintain a reference to an object, and return the object on request.
27
This is used by Registry to make plain objects function similarly
28
to lazily imported objects.
30
Objects can be any sort of python object (class, function, module,
36
def __init__(self, obj):
40
"""Get the module the object was loaded from."""
41
return self._obj.__module__
44
"""Get the object that was saved at creation time"""
48
class _LazyObjectGetter(_ObjectGetter):
49
"""Keep a record of a possible object.
51
When requested, load and return it.
54
__slots__ = ['_module_name', '_member_name', '_imported']
56
def __init__(self, module_name, member_name):
57
self._module_name = module_name
58
self._member_name = member_name
59
self._imported = False
60
super(_LazyObjectGetter, self).__init__(None)
63
"""Get the module the referenced object will be loaded from.
65
return self._module_name
68
"""Get the referenced object.
70
Upon first request, the object will be imported. Future requests will
71
return the imported object.
73
if not self._imported:
74
self._obj = get_named_object(self._module_name, self._member_name)
76
return super(_LazyObjectGetter, self).get_obj()
79
return "<%s.%s object at %x, module=%r attribute=%r imported=%r>" % (
80
self.__class__.__module__, self.__class__.__name__, id(self),
81
self._module_name, self._member_name, self._imported)
84
class Registry(object):
85
"""A class that registers objects to a name.
87
There are many places that want to collect related objects and access them
88
by a key. This class is designed to allow registering the mapping from key
89
to object. It goes one step further, and allows registering a name to a
90
hypothetical object which has not been imported yet. It also supports
91
adding additional information at registration time so that decisions can be
92
made without having to import the object (which may be expensive).
94
The functions 'get', 'get_info', and 'get_help' also support a
95
'default_key' (settable through my_registry.default_key = XXX, XXX must
96
already be registered.) Calling my_registry.get() or my_registry.get(None),
97
will return the entry for the default key.
101
"""Create a new Registry."""
102
self._default_key = None
103
# Map from key => (is_lazy, info)
110
"""Return a set of the format names which are aliases."""
111
return dict(self._aliases.items())
115
for alias, target in self._aliases.items():
116
ret.setdefault(target, []).append(alias)
119
def register(self, key, obj, help=None, info=None,
120
override_existing=False):
121
"""Register a new object to a name.
123
:param key: This is the key to use to request the object later.
124
:param obj: The object to register.
125
:param help: Help text for this entry. This may be a string or
126
a callable. If it is a callable, it should take two
127
parameters (registry, key): this registry and the key that
128
the help was registered under.
129
:param info: More information for this entry. Registry.get_info()
130
can be used to get this information. Registry treats this as an
131
opaque storage location (it is defined by the caller).
132
:param override_existing: Raise KeyErorr if False and something has
133
already been registered for that key. If True, ignore if there
134
is an existing key (always register the new value).
136
if not override_existing:
137
if key in self._dict:
138
raise KeyError('Key %r already registered' % key)
139
self._dict[key] = _ObjectGetter(obj)
140
self._add_help_and_info(key, help=help, info=info)
142
def register_lazy(self, key, module_name, member_name,
143
help=None, info=None,
144
override_existing=False):
145
"""Register a new object to be loaded on request.
147
:param key: This is the key to use to request the object later.
148
:param module_name: The python path to the module. Such as 'os.path'.
149
:param member_name: The member of the module to return. If empty or
150
None, get() will return the module itself.
151
:param help: Help text for this entry. This may be a string or
153
:param info: More information for this entry. Registry.get_info()
154
can be used to get this information. Registry treats this as an
155
opaque storage location (it is defined by the caller).
156
:param override_existing: If True, replace the existing object
157
with the new one. If False, if there is already something
158
registered with the same key, raise a KeyError
160
if not override_existing:
161
if key in self._dict:
162
raise KeyError('Key %r already registered' % key)
163
self._dict[key] = _LazyObjectGetter(module_name, member_name)
164
self._add_help_and_info(key, help=help, info=info)
166
def register_alias(self, key, target, info=None):
167
"""Register an alias.
169
:param key: Alias name
170
:param target: Target key name
172
if key in self._dict and key not in self._aliases:
173
raise KeyError('Key %r already registered and not an alias' % key)
174
self._dict[key] = self._dict[target]
175
self._aliases[key] = target
177
info = self._info_dict[target]
178
self._add_help_and_info(key, help=self._help_dict[target], info=info)
180
def _add_help_and_info(self, key, help=None, info=None):
181
"""Add the help and information about this key"""
182
self._help_dict[key] = help
183
self._info_dict[key] = info
185
def get(self, key=None):
186
"""Return the object register()'ed to the given key.
188
May raise ImportError if the object was registered lazily and
189
there are any problems, or AttributeError if the module does not
190
have the supplied member.
192
:param key: The key to obtain the object for. If no object has been
193
registered to that key, the object registered for self.default_key
194
will be returned instead, if it exists. Otherwise KeyError will be
196
:return: The previously registered object.
197
:raises ImportError: If the object was registered lazily, and there are
198
problems during import.
199
:raises AttributeError: If registered lazily, and the module does not
200
contain the registered member.
202
return self._dict[self._get_key_or_default(key)].get_obj()
204
def _get_module(self, key):
205
"""Return the module the object will be or was loaded from.
207
:param key: The key to obtain the module for.
208
:return: The name of the module
210
return self._dict[key].get_module()
212
def get_prefix(self, fullname):
213
"""Return an object whose key is a prefix of the supplied value.
215
:fullname: The name to find a prefix for
216
:return: a tuple of (object, remainder), where the remainder is the
217
portion of the name that did not match the key.
219
for key in self.keys():
220
if fullname.startswith(key):
221
return self.get(key), fullname[len(key):]
223
def _get_key_or_default(self, key=None):
224
"""Return either 'key' or the default key if key is None"""
227
if self.default_key is None:
228
raise KeyError('Key is None, and no default key is set')
230
return self.default_key
232
def get_help(self, key=None):
233
"""Get the help text associated with the given key"""
234
the_help = self._help_dict[self._get_key_or_default(key)]
235
if callable(the_help):
236
return the_help(self, key)
239
def get_info(self, key=None):
240
"""Get the extra information associated with the given key"""
241
return self._info_dict[self._get_key_or_default(key)]
243
def remove(self, key):
244
"""Remove a registered entry.
246
This is mostly for the test suite, but it can be used by others
250
def __contains__(self, key):
251
return key in self._dict
254
"""Get a list of registered entries"""
255
return sorted(self._dict)
258
for key in self._dict:
259
yield key, self._dict[key].get_obj()
262
# We should not use the iteritems() implementation below (see bug
264
return [(key, self._dict[key].get_obj()) for key in self.keys()]
266
def _set_default_key(self, key):
267
if key not in self._dict:
268
raise KeyError('No object registered under key %s.' % key)
270
self._default_key = key
272
def _get_default_key(self):
273
return self._default_key
275
default_key = property(_get_default_key, _set_default_key,
276
doc="Current value of the default key."
277
" Can be set to any existing key.")
280
class FormatRegistry(Registry):
281
"""Registry specialised for handling formats."""
283
def __init__(self, other_registry=None):
284
Registry.__init__(self)
285
self._other_registry = other_registry
287
def register(self, key, obj, help=None, info=None,
288
override_existing=False):
289
Registry.register(self, key, obj, help=help, info=info,
290
override_existing=override_existing)
291
if self._other_registry is not None:
292
self._other_registry.register(key, obj, help=help,
293
info=info, override_existing=override_existing)
295
def register_lazy(self, key, module_name, member_name,
296
help=None, info=None,
297
override_existing=False):
298
# Overridden to allow capturing registrations to two seperate
299
# registries in a single call.
300
Registry.register_lazy(self, key, module_name, member_name,
301
help=help, info=info, override_existing=override_existing)
302
if self._other_registry is not None:
303
self._other_registry.register_lazy(key, module_name, member_name,
304
help=help, info=info, override_existing=override_existing)
306
def remove(self, key):
307
Registry.remove(self, key)
308
if self._other_registry is not None:
309
self._other_registry.remove(key)
311
def get(self, format_string):
312
r = Registry.get(self, format_string)