1
# Copyright (C) 2006 by 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
"""Functionality to create lazy evaluation objects.
19
This includes waiting to import a module until it is actually used.
25
class ScopeReplacer(object):
26
"""A lazy object that will replace itself in the appropriate scope.
28
This object sits, ready to create the real object the first time it is
32
__slots__ = ('_scope', '_factory', '_name')
34
def __init__(self, scope, factory, name):
35
"""Create a temporary object in the specified scope.
36
Once used, a real object will be placed in the scope.
38
:param scope: The scope the object should appear in
39
:param factory: A callable that will create the real object.
40
It will be passed (self, scope, name)
41
:param name: The variable name in the given scope.
44
self._factory = factory
49
"""Actually replace self with other in the given scope"""
50
factory = object.__getattribute__(self, '_factory')
51
scope = object.__getattribute__(self, '_scope')
52
name = object.__getattribute__(self, '_name')
53
obj = factory(self, scope, name)
58
"""Stop holding on to all the extra stuff"""
63
def __getattribute__(self, attr):
64
obj = object.__getattribute__(self, '_replace')()
65
object.__getattribute__(self, '_cleanup')()
66
return getattr(obj, attr)
68
def __call__(self, *args, **kwargs):
69
obj = object.__getattribute__(self, '_replace')()
70
object.__getattribute__(self, '_cleanup')()
71
return obj(*args, **kwargs)